我有一个嵌套的字典,如下所示
entry = {
0: {"Q": 0},
1: {"W": 2, "E": 3, "N": 5, "S": 4, "Q": 0},
2: {
"N": {
"Q": {"E"}
}
},
}
当我尝试只访问密钥1
的密钥时,我得到了以下信息:
>>> print(entry[1].keys())
dict_keys(['W', 'E', 'N', 'S', 'Q'])
但对于键2,它只返回顶部键,而不返回嵌套键。
>>> print(entry[2].keys())
dict_keys(['N'])
为什么它不返回字典的嵌套键?
发布于 2018-08-09 03:08:24
当您运行print(entry[2].keys())
时
你问python“数据中有哪些键对应于键'2'?(在你的例子中是另一个字典)”,答案就是'N‘。这是因为
entry[2]
是
{"N": { "Q":{"E"}}
其具有单个键'N‘和数据'{"Q":{"E"}}’
发布于 2018-08-09 03:15:11
dict.keys
仅返回字典的顶级键。如果你想得到一个字典的所有嵌套的键,你需要定义你自己的函数。
# interface for dictionary-like objects
from collections.abc import Mapping
def nested_keys(d) -> set:
"""
Return a set containing all nested keys.
"""
# If it is not a dict-like object, return an empty set
if not isinstance(d, Mapping):
return set()
keys = d.keys()
for v in d.values():
# Update the keys set with the keys in each value by using the union (or) operator: |
keys |= nested_keys(v)
return keys
发布于 2018-08-09 03:16:21
如果想要检查所有嵌套的键,可以创建一个循环函数来检查所查找数据的类型,如果它是另一个字典,则对其进行迭代,例如
def print_nested_keys(d):
for k in d.keys():
print(k)
if type(d[k]) == dict:
print('nested dict detected - recursing...')
print_nested_keys(d[k])
在这里,只要字典中的一个键指向另一个字典,就会递归地调用该函数来读取较低级别的字典键。当然,如果您想要这样一个列表,您总是可以将在列表中找到的键附加到函数的末尾返回。
https://stackoverflow.com/questions/51753809
复制相似问题