-
Notifications
You must be signed in to change notification settings - Fork 26
/
ExpandDicts.py
43 lines (37 loc) · 965 Bytes
/
ExpandDicts.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# From a given nested dict, normalize it into dict.
def normalize_dict(input_dict):
'''
Expanding nested dicts into normalized dict using recursion
'''
result = {}
for key, val in input_dict.items():
if isinstance(val, dict):
result.update(normalize_dict(val))
else:
result[key] = val
return result
sample_dict = {
"key1": "val1",
"key2": {
"key2_1": "val2_1",
"key2_2": {
"key2_2_1": "val2_2_1",
"key2_2_2": "val2_2_2",
},
"key2_3": "val2_3"
},
"key3": "val3",
"key4": "val4"
}
output_dict = normalize_dict(sample_dict)
print(output_dict)
## Expected Output
# output_dict = {
# "key1": "val1",
# "key2_1": "val2_1",
# "key2_2_1": "val2_2_1",
# "key2_2_2": "val2_2_2",
# "key2_3": "val2_3",
# "key3": "val3",
# "key4": "val4"
# }