我有一个二维关联数组(字典)。我想使用 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']
我想要的输出:
{'type': 'plant', 'name': 'moe', 'species': 'oak'}
plant
moe
oak
我的实际输出:
two
Traceback (most recent call last):
File "./test.py", line 16, in <module>
print thing['type']
TypeError: string indices must be integers, not str
我错过了什么?
PS我知道我可以做一个for k,v in doubleDict
,但我真的想避免做一个很长的if k == 'type': ... elif k == 'name': ...
陈述。我希望能够thing['type']
直接打电话。