Skip to content

Instantly share code, notes, and snippets.

@fvilante
Created September 11, 2018 15:52
Show Gist options
  • Save fvilante/db4bc8134aa2f6ac497e97c69aea084b to your computer and use it in GitHub Desktop.
Save fvilante/db4bc8134aa2f6ac497e97c69aea084b to your computer and use it in GitHub Desktop.
Python - Convert NamedTuple to Dict to NamedTuple
# tested on python 3.6
from typing import NamedTuple
class T(NamedTuple):
a: int
b: str
if __name__=='__main__':
# define a named tuple object
t = T(20, 'Hello')
# to ordered dict
t1 = t._asdict()
assert(t1 == t)
# back to namedtuple
t4 = T(**dict(t._asdict()))
assert(t4 == t)
# or with string class evaluation
t5 = eval('T')(**dict(t._asdict()))
assert(t5 == t)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment