我有一个二维关联数组(字典)。我想使用for循环迭代第一个维度,并在每次迭代时提取第二个维度的字典。在
例如:
#!/usr/bin/python
doubleDict = dict()
doubleDict['one'] = dict()
doubleDict['one']['type'] = 'animal'
doubleDict['one']['name'] = 'joe'
doubleDict['one']['species'] = 'monkey'
doubleDict['two'] = dict()
doubleDict['two']['type'] = 'plant'
doubleDict['two']['name'] = 'moe'
doubleDict['two']['species'] = 'oak'
for thing in doubleDict:
print thing
print thing['type']
print thing['name']
print thing['species']
我想要的输出:
^{pr2}$我的实际产量:
two
Traceback (most recent call last):
File "./test.py", line 16, in <module>
print thing['type']
TypeError: string indices must be integers, not str
我错过了什么?在
我知道我可以做一个for k,v in doubleDict
,但我真的在努力避免不得不做一个长的if k == 'type': ... elif k == 'name': ...
语句。我希望能直接给thing['type']
打电话。在
dict
s中的For循环遍历键而不是值。在要迭代这些值,请执行以下操作:
我使用了完全相同的代码,但在末尾添加了
.itervalues()
,这意味着:“我想迭代这些值”。在获取嵌套结果的通用方法:
或者
^{pr2}$当你迭代字典时,你迭代的是它的键,而不是它的值。要获取嵌套值,必须执行以下操作:
相关问题 更多 >
编程相关推荐