Set attributes from dictionary in python

后端 未结 7 1662
南旧
南旧 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 10:58

    Why not just use attribute names as keys to a dictionary?

    class StructMyDict(dict):
    
         def __getattr__(self, name):
             try:
                 return self[name]
             except KeyError as e:
                 raise AttributeError(e)
    
         def __setattr__(self, name, value):
             self[name] = value
    

    You can initialize with named arguments, a list of tuples, or a dictionary, or individual attribute assignments, e.g.:

    nautical = StructMyDict(left = "Port", right = "Starboard") # named args
    
    nautical2 = StructMyDict({"left":"Port","right":"Starboard"}) # dictionary
    
    nautical3 = StructMyDict([("left","Port"),("right","Starboard")]) # tuples list
    
    nautical4 = StructMyDict()  # fields TBD
    nautical4.left = "Port"
    nautical4.right = "Starboard"
    
    for x in [nautical, nautical2, nautical3, nautical4]:
        print "%s <--> %s" % (x.left,x.right)
    

    Alternatively, instead of raising the attribute error, you can return None for unknown values. (A trick used in the web2py storage class)

提交回复
热议问题