Forked from Integralist/Python 3: Convert namedtuple into dict so we can convert it to json.py
Created
November 6, 2018 16:04
-
-
Save hungryzi/3754baa798e2af6dfaf292fe9a079b99 to your computer and use it in GitHub Desktop.
Python 3: Convert namedtuple into dict so we can convert it to json
This file contains hidden or 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
import json | |
from collections import namedtuple | |
x = namedtuple('_', ['language', 'country', 'locale'])( | |
'en', | |
'en-GV', | |
'en_US' | |
) | |
nt = x._asdict() | |
print('namedtuple:', nt) | |
# OrderedDict([('language', 'en'), ('country', 'en-GV'), ('locale', 'en_US')]) | |
# Note: if you want to print `nt` as a dict then you'll need to wrap it in a dict(nt) call | |
z = json.dumps(nt) | |
print('json dump:', z) | |
# {"language": "en", "country": "en-GV", "locale": "en_US"} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment