【发布时间】:2015-05-04 21:47:07
【问题描述】:
在这种简化的形式中,我想在迭代类的字典时返回 bar1 的值,以避免需要列表的库出现问题。
class classTest:
def __init__(self, foo):
self.bar1 = foo
def __iter__(self):
for k in self.keys():
yield self[k].bar1
aDict = {}
aDict["foo"] = classTest("xx")
aDict["bar"] = classTest("yy")
for i in aDict:
print i
当前输出为
foo
bar
我的目标是这个输出是
xx
yy
让这个工作我缺少什么?或者这甚至可能吗?
【问题讨论】:
-
您正在迭代
aDict,这是一个产生键的字典。您没有迭代每个单独的值。字典不会将迭代委托给所包含的值。 -
for val in aDict.values()如果你想要这些值
标签: python dictionary iterator