-
Notifications
You must be signed in to change notification settings - Fork 139
/
Copy pathflatten-nested-dictionary.py
52 lines (45 loc) · 1.15 KB
/
flatten-nested-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
"""
#173
Stripe
Write a function to flatten a nested dictionary. Namespace the keys with a period.
For example, given the following dictionary:
{
"key": 3,
"foo": {
"a": 5,
"bar": {
"baz": 8
}
}
}
it should become:
{
"key": 3,
"foo.a": 5,
"foo.bar.baz": 8
}
You can assume keys do not contain dots in them, i.e. no clobbering will occur.
"""
def flattenDictionaryHelper(nestedDict, flattenedDic, currentKey):
for key in nestedDict.keys():
if type(nestedDict[key]) == int:
flattenedDic[(currentKey+"."+key).strip(".")] = nestedDict[key]
else:
flattenedDic = flattenDictionaryHelper(nestedDict[key], flattenedDic, (currentKey+"."+key).strip('.'))
return flattenedDic
def flattenDictionary(nestedDic):
return flattenDictionaryHelper(nestedDic, dict(), "")
def main():
nestedDictionary = {
"key": 3,
"foo": {
"a": 5,
"bar": {
"baz": 8
}
}
}
flattenedDictionary = flattenDictionary(nestedDictionary)
print(flattenedDictionary)
if __name__ == "__main__":
main()