everyone. I have the structure like this:
JavaScript
x
6
1
data = [
2
["apple", "1 apple", "2 apple"],
3
["lemon", "1 lemon", "2 lemon", "3 lemon"],
4
["lemon", "1 orange"]
5
]
6
And want the output like this:
JavaScript
1
17
17
1
{
2
"apple": {
3
"1 apple": {
4
"2 apple": 0
5
}
6
},
7
"lemon": {
8
"1 lemon": {
9
"2 lemon": {
10
"3 lemon": 0
11
}
12
},
13
"1 orange": 0
14
},
15
}
16
17
I have a lot of of lists (chains) in the data
, so I need your help!)
How to do it in python?
Advertisement
Answer
Source : How to merge dictionaries of dictionaries?
JavaScript
1
27
27
1
def merge(a, b, path=None):
2
"merges b into a"
3
if path is None: path = []
4
for key in b:
5
if key in a:
6
if isinstance(a[key], dict) and isinstance(b[key], dict):
7
merge(a[key], b[key], path + [str(key)])
8
elif a[key] == b[key]:
9
pass # same leaf value
10
else:
11
raise Exception('Conflict at %s' % '.'.join(path + [str(key)]))
12
else:
13
a[key] = b[key]
14
return a
15
16
def construct(data):
17
if len(data) == 1:
18
return {data[0]: 0}
19
return {data[0]: construct(data[1:])}
20
21
res = {}
22
for item in data:
23
a = construct(item)
24
res = merge(res, a)
25
print(res)
26
res
27