Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to convert Python dict to class object with fields

📅 2017-Feb-27 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ dict, namedtuple, python ⬩ 📚 Archive

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)

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧