-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathflatten-dict.py
40 lines (36 loc) · 1.31 KB
/
flatten-dict.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
def flatten(dictionary):
stack = [((), dictionary)]
result = {}
while stack:
path, current = stack.pop()
if current:
for k, v in current.items():
if isinstance(v, dict):
stack.append((path + (k,), v))
else:
result["/".join((path + (k,)))] = v
else:
result["/".join(path)] = ""
return result
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert flatten({"key": "value"}) == {"key": "value"}, "Simple"
assert flatten(
{"key": {"deeper": {"more": {"enough": "value"}}}}
) == {"key/deeper/more/enough": "value"}, "Nested"
assert flatten({"empty": {}}) == {"empty": ""}, "Empty value"
assert flatten({"name": {
"first": "One",
"last": "Drone"},
"job": "scout",
"recent": {},
"additional": {
"place": {
"zone": "1",
"cell": "2"}}}
) == {"name/first": "One",
"name/last": "Drone",
"job": "scout",
"recent": "",
"additional/place/zone": "1",
"additional/place/cell": "2"}