Using namedtuple's to convert dicts to objects

pzelnip

Adam Parkin

Posted on August 25, 2023

Using namedtuple's to convert dicts to objects

A friend shared this with me today and I thought it was pretty neat. If you have a dict, and you want to convert it to an object where the object properties are the keys from the dict, and the values are the values from the dict, you can use a namedtuple to do so. For example:

>>> some_dict = {"name": "My name", "func" : "my func"}
>>> import namedtuple
>>> SomeClass = namedtuple("SomeClass", some_dict.keys())
>>> as_an_object = SomeClass(**some_dict)
>>> as_an_object.name
'My name'
>>> as_an_object.func
'my func'

Enter fullscreen mode Exit fullscreen mode

Won't handle nested dicts (the sub-dicts will still be dicts on the constructed object), but for a quick and dirty way to convert a dict to an object, this seems pretty handy.

Using the splat operator you can also save a line of code:

>>> as_an_object = namedtuple("SomeClass", some_dict.keys())(**some_dict)
>>> as_an_object
SomeClass(name='My name', func='my func')
Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
pzelnip
Adam Parkin

Posted on August 25, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related