我有一個二維關聯數組(字典)。我想用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']
。
我認爲你缺少的是'在doubleDict事'在迭代該字典的關鍵字。 – kojiro
如果你想要一個二維字典,其中第一級的關鍵字只是'one','two'等等的東西,爲什麼不只是使用字典列表?列表也有O(1)隨機訪問。 – Shashank