-
Notifications
You must be signed in to change notification settings - Fork 134
/
Flatten_Dictionary.py
58 lines (48 loc) · 1.37 KB
/
Flatten_Dictionary.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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def flatten_dict(initialVal, dictionary, flatDictionary):
for key in dictionary:
value = dictionary[key]
if type(value) is not dict:
if initialVal is None:
flatDictionary[key] = value
else:
flatDictionary[initialVal + '.' + key] = value
else:
if initialVal is None:
flatten_dict(key, value, flatDictionary)
else:
flatten_dict(initialVal + '.' + key, value, flatDictionary)
# iterative solution
def flatten_dict2(dictionary):
flatDictionary = {}
stack = [(dictionary, None)]
while stack:
d, path = stack.pop()
for k, v in d.items():
if path is None:
newkey = k
else:
newkey = '.'.join([path, k])
if isinstance(v, dict):
stack.append((v, newkey))
else:
flatDictionary[newkey] = v
return flatDictionary
if __name__ == '__main__':
flatDictionary = {}
dictionary = {
'Key1': '1',
'Key2': {
'a': '2',
'b': '3',
'c': {
'd': '3',
'e': '1'
}
}
}
# recursive function call
flatten_dict(None, dictionary, flatDictionary)
# iterative function call
f = flatten_dict2(dictionary)
for k in f:
print(k, ":", f[k])