如果我有一本任意深度的字典词典,我如何列出给定深度的字典中的所有键?或者获取字典中的键列表及其深度?
例如,一个简单的字典将是:
dict_o_dicts = {'a': {1:'bob', 2: 'fred', 3: 'henry'},
'b': {2:'fred',3: 'henry', 4: 'pascale'}
}
我想要一个能够做到以下几点的命令:
print keys_at_depth(dict_o_dicts, 0)
将返回:['a','b']
和
print keys_at_depth(dict_o_dicts, 1)
将返回[1,2,3,4]
我可以递归地遍历字典以找到字典的最大深度,但是当我尝试报告深度和键值时,我最终会破坏递归。
由于
答案 0 :(得分:2)
假设所有级别都有效dicts
dict_o_dicts = {'a': {1:'bob', 2: 'fred', 3: 'henry'},
'b': {2:'fred',3: 'henry', 4: 'pascale'} }
from itertools import chain
def keys_at_depth(d, l):
if l == 0: return d.keys()
elif l > 0: return set(chain.from_iterable([keys_at_depth(d[k], l - 1) for k in d]))
print keys_at_depth(dict_o_dicts, 1)
<强>输出强>
set([1, 2, 3, 4])
答案 1 :(得分:2)
此例程将以递归方式返回dict
个set
个密钥的每个深度:
def keys_by_depth(dict_, depth=0, output=None):
if output is None:
output = {}
if not depth in output:
output[depth] = set()
for key in dict_:
output[depth].add(key)
if isinstance(dict_[key], dict):
keys_by_depth(dict_[key], depth+1, output)
return output
给出输出:
{0: {'b', 'a'}, 1: {1, 2, 3, 4}}
请注意,这将适用于每个级别的字典和非dict
值的混合。对于给定深度的密钥,您可以一次呼叫和访问:
>>> print(keys_by_depth(dict_o_dicts)[1])
{1, 2, 3, 4}
答案 2 :(得分:1)
递归方法:
def key_at_depth(dct, dpt):
if dpt > 0:
return [ key for subdct in dct.itervalues() for key in key_at_depth(subdct, dpt-1) ]
else:
return dct.keys()
dict_o_dicts = {'a': {1:'bob', 2: 'fred', 3: 'henry'}, 'b': {2:'fred',3: 'henry', 4: 'pascale'} }
key_at_depth(dict_o_dicts, 0)
Out[69]: ['a', 'b']
key_at_depth(dict_o_dicts, 1)
Out[70]: [1, 2, 3, 2, 3, 4]
答案 3 :(得分:0)
您似乎正在使用树结构,并且您希望获得给定级别的节点。阅读你的帖子,我意识到可能在同一级别存在更多的词典。所以我在这里发布的解决方案将返回给定级别所有字典的所有键。
keys=[]
def keys_at_level(tree, level):
# TODO: Eliminate that ugly global var keys.
if level == 0: # Adjust this contition to your needs (0 or 1)
# Calculate keys.
global keys
keys.extend(tree.keys())
else:
# Iter throught values and ask for dicts.
values = tree.values()
for value in values:
if isinstance(value, dict):
keys_at_level(value, level-1)
keys_at_level(tree, 0)
print keys
# If you don't want duplicates just do:
keys = set(keys)