I have a nested dict of the folling form:
JavaScript
x
2
1
dict1 = {layer1: {layer2: {layer3: {a:None, b:None, c:None}}, {d:None, e:None}}}
2
And a flat dict with only the values in the final layer:
JavaScript
1
2
1
dict2 = {a:1, b:2, c:3, d:4, e:5}
2
My expected output after filling the values in the first dict would be:
JavaScript
1
2
1
dict_out = {layer1: {layer2: {layer3: {a:1, b:2, c:3}}, {d:4, e:5}}}
2
How should I approach this?
Advertisement
Answer
I hope I’ve understood your question correctly. You can use recursion to replace the values of keys in-place:
JavaScript
1
26
26
1
dct = {
2
"layer1": {
3
"layer2": {"layer3": {"a": 0, "b": 0, "c": 0}},
4
"layer4": {"d": 0, "e": 0},
5
}
6
}
7
8
dct2 = {"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}
9
10
11
def replace(d):
12
if isinstance(d, dict):
13
for k in d & dct2.keys():
14
d[k] = dct2[k]
15
16
for k in d - dct2.keys():
17
replace(d[k])
18
19
elif isinstance(d, list):
20
for i in d:
21
replace(i)
22
23
24
replace(dct)
25
print(dct)
26
Prints:
JavaScript
1
7
1
{
2
"layer1": {
3
"layer2": {"layer3": {"a": 1, "b": 2, "c": 3}},
4
"layer4": {"d": 4, "e": 5},
5
}
6
}
7