« Back to Index

Python 3: Convert namedtuple into dict so we can convert it to json

View original Gist on GitHub

Python 3: Convert namedtuple into dict so we can convert it to json.py

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"}