迭代二维dict以删除di

2024-10-01 07:41:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个二维关联数组(字典)。我想使用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']打电话。在


Tags: nameinfor字典binusrtype数组
3条回答

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)

或者

^{pr2}$

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

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

相关问题 更多 >