Skip to content

Instantly share code, notes, and snippets.

@ashwin
Created February 27, 2017 15:24
Show Gist options
  • Save ashwin/179389f1f6a64875710eee772d752f50 to your computer and use it in GitHub Desktop.
Save ashwin/179389f1f6a64875710eee772d752f50 to your computer and use it in GitHub Desktop.
How to convert Python dict to class object with fields
>>> from collections import namedtuple
>>> d = {"name": "joe", "age": 20}
>>> d
{'age': 20, 'name': 'joe'}
>>> d_named = namedtuple("Employee", d.keys())(*d.values())
>>> d_named
Employee(name='joe', age=20)
>>> d_named.name
'joe'
Copy link

ghost commented Oct 18, 2017

Also it can will raise ValueError exception if field names start with an underscore

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