我想买一本这样的字典:
{1:{2:{3:{4:'foo'}}}}
看起来像这样:
^{2}$词典嵌套到未知深度。这无疑是在测试我的递归知识。在
到目前为止我有这个。我觉得这很管用。然而,我想知道是否有一种更像Python的方式来做到这一点:
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
您可以跟踪已看到的关键点:
输出:
^{pr2}$但是,只有当每个字典只有一个键时,上述解决方案才有效。要一般地查找所有路径,请使用
yield
:输出:
相关问题 更多 >
编程相关推荐