File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ Title: Using namedtuple's to convert dicts to objects
2+ Date: 2023-08-25 15:06
3+ Modified: 2023-08-25 15:06
4+ Category: Posts
5+ tags: python,dict,namedtuple
6+ cover: static/imgs/python-logo-master-v3-TM.png
7+ summary: Quick and dirty way to convert a dict into an object in Python using namedtuple's
8+
9+ A friend shared this with me today and I thought it was pretty neat. If you have a dict, and
10+ you want to convert it to an object where the object properties are the keys from the dict, and
11+ the values are the values from the dict, you can use a namedtuple to do so. For example:
12+
13+ ``` python
14+ >> > some_dict = {" name" : " My name" , " func" : " my func" }
15+ >> > import namedtuple
16+ >> > SomeClass = namedtuple(" SomeClass" , some_dict.keys())
17+ >> > as_an_object = SomeClass(** some_dict)
18+ >> > as_an_object.name
19+ ' My name'
20+ >> > as_an_object.func
21+ ' my func'
22+ ```
23+
24+ Won't handle nested dicts (the sub-dicts will still be dicts on the constructed object), but
25+ for a quick and dirty way to convert a dict to an object, this seems pretty handy.
26+
27+ Using the splat operator you can also save a line of code:
28+
29+ ``` python
30+ >> > as_an_object = namedtuple(" SomeClass" , some_dict.keys())(** some_dict)
31+ >> > as_an_object
32+ SomeClass(name = ' My name' , func = ' my func' )
33+ ```
You can’t perform that action at this time.
0 commit comments