Set attributes from dictionary in python

后端 未结 7 1689
南旧
南旧 2020-11-27 10:50

Is it possible to create an object from a dictionary in python in such a way that each key is an attribute of that object?

Something like this:

 d =          


        
7条回答
  •  没有蜡笔的小新
    2020-11-27 11:10

    I think that answer using settattr are the way to go if you really need to support dict.

    But if Employee object is just a structure which you can access with dot syntax (.name) instead of dict syntax (['name']), you can use namedtuple like this:

    from collections import namedtuple
    
    Employee = namedtuple('Employee', 'name age')
    e = Employee('noname01', 6)
    print e
    #>> Employee(name='noname01', age=6)
    
    # create Employee from dictionary
    d = {'name': 'noname02', 'age': 7}
    e = Employee(**d)
    print e
    #>> Employee(name='noname02', age=7)
    print e._asdict()
    #>> {'age': 7, 'name': 'noname02'}
    

    You do have _asdict() method to access all properties as dictionary, but you cannot add additional attributes later, only during the construction.

提交回复
热议问题