Code Yarns ‍👨‍💻

How to convert Python dict to class object with fields

(First posted on: 2017-02-27 15:25:29+00:00)

A Python dict is extremely versatile. However, there might be situations where you want to access the dict as if it were a class object and the keys were its fields.

This can be easily done by using a namedtuple. Just give it a name and the use the keys to populate its named fields. Set the values for those fields by passing the values from the dict. It all boils down to a single line.

This example code demonstrates the above:

>>> 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)