2013-09-23 109 views
0

我有一個二維關聯數組(字典)。我想用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']

+0

我認爲你缺少的是'在doubleDict事'在迭代該字典的關鍵字。 – kojiro

+1

如果你想要一個二維字典,其中第一級的關鍵字只是'one','two'等等的東西,爲什麼不只是使用字典列表?列表也有O(1)隨機訪問。 – Shashank

回答

3

for循環的鑰匙在dict小號迭代並沒有結束的值。

遍歷值做:

for thing in doubleDict.itervalues(): 
     print thing 
     print thing['type'] 
     print thing['name'] 
     print thing['species'] 

我用你的完全相同的代碼,但在最後添加的.itervalues()意思是:「我要遍歷值」。

4

當你遍歷一個字典時,你遍歷它的鍵而不是它的值。爲了得到嵌套的值,你要做的:

for thing in doubleDict: 
    print doubleDict[thing] 
    print doubleDict[thing]['type'] 
    print doubleDict[thing]['name'] 
    print doubleDict[thing]['species'] 
2

一個通用的方法去嵌套結果:

for thing in doubleDict.values(): 
    print(thing) 
    for vals in thing.values(): 
    print(vals) 

for thing in doubleDict.values(): 
    print(thing) 
    print('\n'.join(thing.values())) 
0

你可以用@ Haidro的答案,但使其與雙迴路更通用:

for key1 in doubleDict: 
    print(doubleDict[key1]) 
    for key2 in doubleDict[key1]: 
     print(doubleDict[key1][key2]) 


{'type': 'plant', 'name': 'moe', 'species': 'oak'} 
plant 
moe 
oak 
{'type': 'animal', 'name': 'joe', 'species': 'monkey'} 
animal 
joe 
monkey 
0

這些所有工作......但看着你的代碼,爲什麼不使用命名的元組呢?

從集合導入namedtuple

LivingThing = namedtuple( 'LivingThing', '類型名稱物種')

doubledict [ '一個'] = LivingThing(類型= '動物',名字=「喬,物種= '猴子')

doubledict [ '一'。名字 doubledict [ '一'] ._ asdict [ '名']