Last active
March 26, 2017 01:00
-
-
Save Nyahua/c26e5f9d473ebca272f180088dc62aa3 to your computer and use it in GitHub Desktop.
flatten embedded children dictionaries in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
# In[31]: | |
dict_list = [ | |
{'id': 1, 'key1': 'abc'}, | |
{'id': 2, 'key1': 'def', 'key2': 123}, | |
{'id': 3, 'key1': 'ghi', 'key2': 456, 'children': [ | |
{'id': 4, 'key1': 'jkl'}, | |
{'id': 5, 'key1': 'mno', 'children': [ | |
{'id': 6, 'key2': 789} | |
]} | |
]}, | |
{'id': 7, 'key1': 'xyz', 'key2': 5893} | |
] | |
# In[34]: | |
def removekey(d, key, deepth): | |
r = dict(d) | |
if key in d: del r[key] | |
r['deepth'] = deepth | |
return r | |
def flat_dict(j, child_key, deepth=0): | |
l = [] | |
for i in j: | |
l += [removekey(i, child_key, deepth)] | |
if child_key in i: | |
l += flat_dict(i[child_key], child_key, deepth = deepth + 1) | |
return l | |
# In[35]: | |
print(flat_dict(dict_list, "children")) | |
# In[ ]: | |
_ = ''' | |
[{'deepth': 0, 'id': 1, 'key1': 'abc'}, | |
{'deepth': 0, 'id': 2, 'key1': 'def', 'key2': 123}, | |
{'deepth': 0, 'id': 3, 'key1': 'ghi', 'key2': 456}, | |
{'deepth': 1, 'id': 4, 'key1': 'jkl'}, | |
{'deepth': 1, 'id': 5, 'key1': 'mno'}, | |
{'deepth': 2, 'id': 6, 'key2': 789}, | |
{'deepth': 0, 'id': 7, 'key1': 'xyz', 'key2': 5893}] | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment