将字符串的值视为...属性名称?

时间:2011-07-18 15:46:15

标签: python

说我有dict

d = {
    'eggs': 4,
    'cheese': 6,
    'coconuts': 8,
}

是否可以遍历字典,创建以键命名的变量,为它们分配相应的值?

eggs = 4
cheese = 6
coconuts = 8

或者也许在对象里面?

self.eggs = 4
self.cheese = 6
self.coconuts = 8

这可能吗?

3 个答案:

答案 0 :(得分:6)

>>> d = {
...     'eggs': 4,
...     'cheese': 6,
...     'coconuts': 8,
... }
>>> globals().update(d)
>>> eggs
4
>>> cheese
6
>>> coconuts
8
>>> d
{'cheese': 6, 'eggs': 4, 'coconuts': 8}

但是对于课程来说,它更容易(更安全),只需使用:

for item, value in d.items():
     setattr(some_object, item, value) #or self.setattr(item, value)

答案 1 :(得分:4)

您可以使用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

答案 2 :(得分:2)

使用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)