Say I have a dict
:
d = {
'eggs': 4,
'cheese': 6,
'coconuts': 8,
}
Is is possible to loop over the dictionary, creating variables named after the keys, assigning them the corresponding value?
eggs = 4
chee开发者_如何学运维se = 6
coconuts = 8
Or maybe inside an object?
self.eggs = 4
self.cheese = 6
self.coconuts = 8
Is this possible?
>>> d = {
... 'eggs': 4,
... 'cheese': 6,
... 'coconuts': 8,
... }
>>> globals().update(d)
>>> eggs
4
>>> cheese
6
>>> coconuts
8
>>> d
{'cheese': 6, 'eggs': 4, 'coconuts': 8}
But for classes, it is easier(safer), just use:
for item, value in d.items():
setattr(some_object, item, value) #or self.setattr(item, value)
You could use Alex Martelli's Bunch class:
>>> class Bunch(object):
... def __init__(self, **kwds):
... self.__dict__.update(kwds)
...
>>> d = {
... 'eggs': 4,
... 'cheese': 6,
... 'coconuts': 8,
... }
>>> b = Bunch(**d)
>>> b.eggs
4
Use setattr:
d = {
'eggs': 4,
'cheese': 6,
'coconuts': 8,
}
class Food: pass
food = Food()
for item in d.iteritems():
setattr(food, *item)
print(food.eggs, food.cheese, food.coconuts)
精彩评论