每個人。我有這樣的結構:
data = [
["apple", "1 apple", "2 apple"],
["lemon", "1 lemon", "2 lemon", "3 lemon"],
["lemon", "1 orange"]
]
并想要這樣的輸出:
{
"apple": {
"1 apple": {
"2 apple": 0
}
},
"lemon": {
"1 lemon": {
"2 lemon": {
"3 lemon": 0
}
},
"1 orange": 0
},
}
我在 中有很多串列(鏈)data,所以我需要你的幫助!)如何在 python 中做到這一點?
uj5u.com熱心網友回復:
來源:如何合并字典的字典?
def merge(a, b, path=None):
"merges b into a"
if path is None: path = []
for key in b:
if key in a:
if isinstance(a[key], dict) and isinstance(b[key], dict):
merge(a[key], b[key], path [str(key)])
elif a[key] == b[key]:
pass # same leaf value
else:
raise Exception('Conflict at %s' % '.'.join(path [str(key)]))
else:
a[key] = b[key]
return a
def construct(data):
if len(data) == 1:
return {data[0]: 0}
return {data[0]: construct(data[1:])}
res = {}
for item in data:
a = construct(item)
res = merge(res, a)
print(res)
res
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/339437.html
上一篇:如何檢查嵌套串列中的所有方塊并列印它們的索引(如坐標)?
下一篇:在同一索引上附加專案
