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'
>>> 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'
>>> 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')
>>> as_an_object = namedtuple("SomeClass", some_dict.keys())(**some_dict)
>>> as_an_object
SomeClass(name='My name', func='my func')
>>> 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

原文链接:Using namedtuple’s to convert dicts to objects

© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
Turn your face to the sun and the shadows fall behind you.
永远面向阳光,这样你就看不见阴影了
评论 抢沙发

请登录后发表评论

    暂无评论内容