-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathflatten.py
50 lines (42 loc) · 1.16 KB
/
flatten.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
def flatten(d,sep="_"):
import collections
obj = collections.OrderedDict()
def recurse(t,parent_key=""):
if isinstance(t,list):
for i in range(len(t)):
recurse(t[i],parent_key + sep + str(i) if parent_key else str(i))
elif isinstance(t,dict):
for k,v in t.items():
recurse(v,parent_key + sep + k if parent_key else k)
else:
obj[parent_key] = t
recurse(d)
return obj
## TEST EXECUTION BELOW ##
from pprint import pprint
data = {
"id": 1,
"first_name": "Jonathan",
"last_name": "Hsu",
"employment_history": [
{
"company": "Black Belt Academy",
"title": "Instructor",
"something": {
"hello": [1,2,3,{
"something":"goes"
}]
}
},
{
"company": "Zerion Software",
"title": "Solutions Engineer"
}
],
"education": {
"bachelors": "Information Technology",
"masters": "Applied Information Technology",
"phd": "Higher Education"
}
}
pprint(flatten(data),indent=2)