Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save hungryzi/3754baa798e2af6dfaf292fe9a079b99 to your computer and use it in GitHub Desktop.
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
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