Python 反转未知深度的嵌套字典
我正在尝试获取一本如下所示的词典:Python 反转未知深度的嵌套字典,python,dictionary,recursion,Python,Dictionary,Recursion,我正在尝试获取一本如下所示的词典: {1:{2:{3:{4:'foo'}}}} 'foo': [1,2,3,4] 看起来像这样: {1:{2:{3:{4:'foo'}}}} 'foo': [1,2,3,4] 字典嵌套到未知深度。这绝对是在测试我的递归知识 到目前为止,我有这个。我认为这是可行的。然而,我想知道是否有一种更像蟒蛇的方式: def denest(nested_dict): denested_dict = {} for k, v in nested_dict.i
{1:{2:{3:{4:'foo'}}}}
'foo': [1,2,3,4]
看起来像这样:
{1:{2:{3:{4:'foo'}}}}
'foo': [1,2,3,4]
字典嵌套到未知深度。这绝对是在测试我的递归知识
到目前为止,我有这个。我认为这是可行的。然而,我想知道是否有一种更像蟒蛇的方式:
def denest(nested_dict):
denested_dict = {}
for k, v in nested_dict.items():
if isinstance(v, dict):
sub_dict = denest(v)
for t, s in sub_dict.items():
sub_dict[t] +=[k]
denested_dict.update(sub_dict)
else:
denested_dict[v] = [k]
return denested_dict
您可以跟踪已看到的关键点:
def build_new(_d, seen = []):
[[a, b]] = _d.items()
return {b:seen+[a]} if not isinstance(b, dict) else build_new(b, seen+[a])
print(build_new({1:{2:{3:{4:'foo'}}}}))
输出:
{'foo': [1, 2, 3, 4]}
[{'bar': [1, 2, 3]}, {'foo': [1, 2, 4]}, {'stuff': [1, 2, 5, 6]}]
但是,只有当每个字典只有一个键时,上述解决方案才会起作用。要常规查找所有路径,请使用yield
:
def all_paths(d, seen = []):
for a, b in d.items():
if not isinstance(b, dict):
yield {b:seen+[a]}
else:
yield from all_paths(b, seen+[a])
d = {1:{2:{3:'bar', 4:'foo', 5:{6:'stuff'}}}}
print(list(all_paths(d)))
输出:
{'foo': [1, 2, 3, 4]}
[{'bar': [1, 2, 3]}, {'foo': [1, 2, 4]}, {'stuff': [1, 2, 5, 6]}]
您可以跟踪已看到的关键点:
def build_new(_d, seen = []):
[[a, b]] = _d.items()
return {b:seen+[a]} if not isinstance(b, dict) else build_new(b, seen+[a])
print(build_new({1:{2:{3:{4:'foo'}}}}))
输出:
{'foo': [1, 2, 3, 4]}
[{'bar': [1, 2, 3]}, {'foo': [1, 2, 4]}, {'stuff': [1, 2, 5, 6]}]
但是,只有当每个字典只有一个键时,上述解决方案才会起作用。要常规查找所有路径,请使用yield
:
def all_paths(d, seen = []):
for a, b in d.items():
if not isinstance(b, dict):
yield {b:seen+[a]}
else:
yield from all_paths(b, seen+[a])
d = {1:{2:{3:'bar', 4:'foo', 5:{6:'stuff'}}}}
print(list(all_paths(d)))
输出:
{'foo': [1, 2, 3, 4]}
[{'bar': [1, 2, 3]}, {'foo': [1, 2, 4]}, {'stuff': [1, 2, 5, 6]}]
如果其中一个嵌套字典中有一个额外的键呢?是否要将多个列表链接到每个路径?在处理此类嵌套数据结构时,您可能会发现我的方法很有帮助。如果其中一个嵌套字典中有一个附加键,该怎么办?是否要将多个列表链接到每个路径?在处理类似这样的嵌套数据结构时,您可能会发现我的方法很有用。@eljusticero67不要在多个dict上调用这些函数。它们无法正常工作,因为
seen
是一个可变的默认参数,因此它充当缓存,我应该提到的是,您可以通过传递一个空列表作为seen
arg来绕过这个问题。有关此主题的更多信息,请参阅@eljusticero67不要在多个dict上调用这些函数。它们无法正常工作,因为seen
是一个可变的默认参数,因此它充当缓存,我应该提到的是,您可以通过传递一个空列表作为seen
arg来绕过这个问题。有关此主题的更多信息,请参阅