Created
September 11, 2018 15:52
-
-
Save fvilante/db4bc8134aa2f6ac497e97c69aea084b to your computer and use it in GitHub Desktop.
Python - Convert NamedTuple to Dict to NamedTuple
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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