Python 迭代二维dict以删除dict

Python 迭代二维dict以删除dict,python,for-loop,dictionary,multidimensional-array,Python,For Loop,Dictionary,Multidimensional Array,我有一个二维关联数组字典。我想使用for循环迭代第一个维度,并在每次迭代时提取第二个维度的字典 例如: #!/usr/bin/python doubleDict = dict() doubleDict['one'] = dict() doubleDict['one']['type'] = 'animal' doubleDict['one']['name'] = 'joe' doubleDict['one']['species'] = 'monkey' doubleDict['two'] = di

我有一个二维关联数组字典。我想使用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我知道我可以在doubleDict中为k,v做a,但我真的试图避免在k==‘type’时做长的运算。。。elif k=='name':。。。陈述我希望能够直接调用thing['type'.

当你遍历字典时,你遍历的是它的键,而不是它的值。要获取嵌套值,必须执行以下操作:

for thing in doubleDict:
    print doubleDict[thing]
    print doubleDict[thing]['type']
    print doubleDict[thing]['name']
    print doubleDict[thing]['species']
dicts中的For循环迭代键,而不是值

要迭代这些值,请执行以下操作:

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

我使用了与您完全相同的代码,但在末尾添加了.itervalues,这意味着:我希望迭代这些值。

获得嵌套结果的一般方法:

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


您可以使用@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

这些都有用。。。但是看看你的代码,为什么不使用命名元组呢

从集合导入namedtuple

LivingThing=namedtuple'LivingThing','type name species'

doubledict['one']=LivingThingtype='animal',name='joe',species='monkey'

doubledict['one'].名称
doubledict['one'].\u asdict['name']

我认为您缺少的是doubledict中的for东西是迭代该dict的键。如果您想要一个二维字典,其中第一级的键就是“一”、“二”等。为什么不使用字典列表呢?列表也有O1随机访问。
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