Created
February 27, 2017 15:24
-
-
Save ashwin/179389f1f6a64875710eee772d752f50 to your computer and use it in GitHub Desktop.
How to convert Python dict to class object with fields
This file contains 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
>>> 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' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also it can will raise ValueError exception if field names start with an underscore