Python 获取嵌套字典的所有键
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39233973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get all keys of a nested dictionary
提问by Krishn
I have the below code which currently just prints the values of the initial dictionary. However I would like to iterate through every key of the nested dictionary to initially just print the names. Please see my code below:
我有以下代码,目前只打印初始字典的值。但是,我想遍历嵌套字典的每个键以最初只打印名称。请看我下面的代码:
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)
采纳答案by Nikolay Zinov
Here is code that would print all team members:
这是打印所有团队成员的代码:
for k, v in Liverpool.items():
for k1, v1 in v.items():
print(k1)
So you just iterate every inner dictionary one by one and print values.
所以你只需一个一个地迭代每个内部字典并打印值。
回答by Dmitry Torba
In other answers, you were pointed to how to solve your task for given dicts, with maximum depth level equaling to two. Here is the program that will alows you to loop through key-value pair of a dict with unlimited number of nesting levels (more generic approach):
在其他答案中,您被指出如何解决给定字典的任务,最大深度级别等于 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)
Prints
印刷
1 2
3 4
5 6
That is relevant if you are interested only in key-value pair on deepest level (when value is not dict). If you are also interested in key-value pair where value is dict, make a small edit:
如果您只对最深层的键值对感兴趣(当 value 不是 dict 时),这是相关的。如果您也对 value 为 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)
Prints
印刷
a {1: {1: 2, 3: 4}, 2: {5: 6}}
1 {1: 2, 3: 4}
1 2
3 4
2 {5: 6}
5 6
回答by Kevin London
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())
Yields:
产量:
['Alberto Moreno', 'Joe Gomez', 'Dejan Lovren', 'Ragnar Klavan', 'Joel Matip', 'Nathaniel Clyne', 'Mamadou Sakho']
['Alex Manninger', 'Loris Karius', 'Simon Mignolet']