获取嵌套字典的所有键

Kri*_*shn 12 python dictionary nested python-3.x

我有下面的代码,目前只打印初始字典的值.但是,我想迭代嵌套字典的每个键,最初只打印名称.请参阅下面的代码:

Liverpool = {
    'Keepers':{'Loris Karius':1,'Simon Mignolet':2,'Alex Manninger':3},
    'Defenders':{'Nathaniel Clyne':3,'Dejan Lovren':4,'Joel Matip':5,'Alberto Moreno':6,'Ragnar Klavan':7,'Joe Gomez':8,'Mamadou Sakho':9}
}

for k,v in Liverpool.items():
    if k =='Defenders':
       print(v)
Run Code Online (Sandbox Code Playgroud)

Dmi*_*rba 28

在其他答案中,您被指出如何解决给定dicts的任务,最大深度等级为2.这是一个程序,它将允许您循环遍历具有无限数量嵌套级别的dict的键值对(更通用的方法):

def recursive_items(dictionary):
    for key, value in dictionary.items():
        if type(value) is dict:
            yield from recursive_items(value)
        else:
            yield (key, value)

a = {'a': {1: {1: 2, 3: 4}, 2: {5: 6}}}

for key, value in recursive_items(a):
    print(key, value)
Run Code Online (Sandbox Code Playgroud)

打印

1 2
3 4
5 6
Run Code Online (Sandbox Code Playgroud)

如果您只对最深层次的键值对感兴趣(当值不是dict时),则这是相关的.如果您对值为dict的键值对感兴趣,请进行小编辑:

def recursive_items(dictionary):
    for key, value in dictionary.items():
        if type(value) is dict:
            yield (key, value)
            yield from recursive_items(value)
        else:
            yield (key, value)

a = {'a': {1: {1: 2, 3: 4}, 2: {5: 6}}}

for key, value in recursive_items(a):
    print(key, value)
Run Code Online (Sandbox Code Playgroud)

打印

a {1: {1: 2, 3: 4}, 2: {5: 6}}
1 {1: 2, 3: 4}
1 2
3 4
2 {5: 6}
5 6
Run Code Online (Sandbox Code Playgroud)

  • 这不处理字典在列表中的情况 (3认同)

小智 13

这是打印所有团队成员的代码:

for k, v in Liverpool.items():
    for k1, v1 in v.items():
        print(k1)
Run Code Online (Sandbox Code Playgroud)

因此,您只需逐个迭代每个内部字典并打印值.

  • 这个答案不会检查内部级别本身是否是字典,否则会导致错误。 (11认同)