假設我有一本字典:
{"a": {"b": 1,
"c": 2,
"d": {"e": 3,
"f": 4,
}
}
"g": {"h": 5,
"i": 6
}
}
我一直在嘗試找到一種方法將此字典映射到每個最終值的“路徑”串列中,如下所示:
[
{"a": {"b": 1}},
{"a": {"c": 2}},
{"a": {"d": {"e": 3}}},
{"a": {"d": {"f": 4}}},
{"g": {"h": 5}},
{"g": {"i": 6}}
]
其中每個串列條目都是單鍵嵌套字典。我認為這可以使用某種形式的深度優先遞回遍歷來完成,但我對遞回函式的編程不是很熟悉,也不知道這是否是最好的方法。
任何輸入將不勝感激。
uj5u.com熱心網友回復:
我同意你的觀點,遞回是一種好方法。這就是我要做的。使用生成器(即產生值)的優點是我們不必使用變數來收集各個結果項。
該變數_revpath
包含導致值的 dict 鍵的“路徑”,但順序相反,因為在遞回結束時,我們希望創建一個從內部到外部 dict 的嵌套 dict。
test = {"a": {"b": 1,
"c": 2,
"d": {"e": 3,
"f": 4,
}
},
"g": {"h": 5,
"i": 6
}
}
def walkdict(d, _revpath=[]):
if isinstance(d, dict):
for key, value in d.items():
yield from walkdict(value, [key] _revpath)
else:
for key in _revpath:
d = {key: d}
yield d
print(list(walkdict(test)))
uj5u.com熱心網友回復:
使用遞回來構建您通過的節點串列
def paths(values, parents=None):
results = []
parents = parents or []
for k, v in values.items():
if isinstance(v, int):
results.append(keys_to_nested_dict([*parents, k], v))
else:
results.extend(paths(v, [*parents, k]))
return results
然后,當您到達葉子時,int
將節點串列轉換為嵌套字典
def keys_to_nested_dict(keys, value):
result = {}
tmp = result
for k in keys[:-1]:
tmp[k] = {}
tmp = tmp[k]
tmp[keys[-1]] = value
return result
print(keys_to_nested_dict(['a', 'b', 'c'], 1)) # {'a': {'b': {'c': 1}}}
x = {"a": {"b": 1, "c": 2, "d": {"e": 3, "f": 4, }},
"g": {"h": 5, "i": 6}}
print(paths(x))
# [{'a': {'b': 1}}, {'a': {'c': 2}}, {'a': {'d': {'e': 3}}}, {'a': {'d': {'f': 4}}}, {'g': {'h': 5}}, {'g': {'i': 6}}]
uj5u.com熱心網友回復:
不完全相同的輸出,但稍作調整可以讓你付出很多努力和復雜性
sample = {"a": {"b": 1,"c": 2,"d": {"e": 3,"f": 4}},"g": {"h": 5,"i": 6}}
from pandas.io.json._normalize import nested_to_record
flat = nested_to_record(sample, sep='_')
輸出
{'a_b': 1, 'a_c': 2, 'a_d_e': 3, 'a_d_f': 4, 'g_h': 5, 'g_i': 6}
現在,每當您想知道可能的路徑時,只需遍歷此字典的鍵 & split('_') 將為您提供整個路徑和相關值
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/494490.html