Skip to content

Instantly share code, notes, and snippets.

@trauber
Created April 22, 2020 18:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trauber/46209f315343f19754e15e1da40e267a to your computer and use it in GitHub Desktop.
Save trauber/46209f315343f19754e15e1da40e267a to your computer and use it in GitHub Desktop.

Python Namedtuple to Dict to JSON

I've patched this together from several different tutorials.

from collections import namedtuple
import json

dict_list = []

Employee = namedtuple('Employee', 'FirstName, LastName, ID')
names_list = [['Michael', 'Jordan', '224567'], ['Kyle', 'Hynes', '294007'], ['Josef', 'Jones', '391107']]
employee_list = map(Employee._make, names_list)

for e in employee_list:
    dict_list.append(e._asdict())

y = json.dumps(dict_list)

print(y)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment