我有下面的代码,目前只打印初始字典的值。但是,我想迭代嵌套字典的每个键,最初只打印名称。请参阅下面的代码:
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)
答案 0 :(得分:21)
在其他答案中,您被指出如何解决给定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)
打印
1 2
3 4
5 6
如果您只对最深层次的键值对感兴趣(当值不是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)
打印
a {1: {1: 2, 3: 4}, 2: {5: 6}}
1 {1: 2, 3: 4}
1 2
3 4
2 {5: 6}
5 6
答案 1 :(得分:12)
以下是打印所有团队成员的代码:
for k, v in Liverpool.items():
for k1, v1 in v.items():
print(k1)
因此,您只需逐个迭代每个内部字典并打印值。
答案 2 :(得分:1)
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():
print(v.keys())
收率:
['Alberto Moreno', 'Joe Gomez', 'Dejan Lovren', 'Ragnar Klavan', 'Joel Matip', 'Nathaniel Clyne', 'Mamadou Sakho']
['Alex Manninger', 'Loris Karius', 'Simon Mignolet']