DEV Community

Adam Parkin
Adam Parkin

Posted on • Originally published at codependentcodr.com on

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

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay