-
Notifications
You must be signed in to change notification settings - Fork 3
/
173_Stripe_Flatten_Nested_Dict.py
executable file
·65 lines (51 loc) · 1.22 KB
/
173_Stripe_Flatten_Nested_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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
"""
This problem was asked by 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.
"""
add_to_basekey = lambda basekey, key: basekey + "." + key
def get_keys(d:dict):
try:
return list(d.keys())
except AttributeError:
return None
def flatten_dict(dictionary:dict):
flat_dict = {}
def helper(basekey, values):
if isinstance(values, dict):
# that means "values" to this "key" were a dict
for k in get_keys(values):
helper(add_to_basekey(basekey, k), values[k])
else:
# values was not a dict for this key
flat_dict[basekey] = values
for key in get_keys(d):
helper(key, dictionary[key])
return flat_dict
if __name__ == '__main__':
d = {
"key": 3,
"foo": {
"a": 5,
"bar": {
"baz": 8
}
}
}
print(flatten_dict(d))