-
Notifications
You must be signed in to change notification settings - Fork 0
/
173.py
62 lines (48 loc) · 1.16 KB
/
173.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
59
60
61
62
"""
Problem:
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.
"""
from typing import Any, Dict
def flatten_dictionary(dictionary: Dict[str, Any]) -> Dict[str, Any]:
for key in list(dictionary.keys()):
value = dictionary[key]
if type(value) == dict:
value = flatten_dictionary(value)
del dictionary[key]
for nested_dictionary_key in value:
dictionary[f"{key}.{nested_dictionary_key}"] = value[
nested_dictionary_key
]
return dictionary
if __name__ == "__main__":
print(flatten_dictionary({
"key": 3,
"foo": {
"a": 5,
"bar": {
"baz": 8
}
}
}))
"""
SPECS:
TIME COMPLEXITY: O(number of key-value pairs)
SPACE COMPLEXITY: O(levels of nesting)
"""