Last active
April 14, 2021 21:11
-
-
Save Integralist/b25185f91ebc8a56fe070d499111b447 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