recursion - Traverse a dictionary recursively in Python? -


what better way traverse dictionary recursively? can lambda or/and list comprehension?

i have:

[   {     "id": 1,     "children": [       {         "id": 2,         "children": []       }     ]   },   {     "id": 3,     "children": []   },   {     "id": 4,     "children": [       {         "id": 5,         "children": [           {             "id": 6,             "children": [               {                 "id": 7,                 "children": []               }             ]           }         ]       }     ]   } ] 

i want:

[1,2,3,4,5,6,7]

you can recursively traverse dictionaries, generic generator function, this

def rec(current_object):     if isinstance(current_object, dict):         yield current_object["id"]         item in rec(current_object["children"]):             yield item     elif isinstance(current_object, list):         items in current_object:             item in rec(items):                 yield item  print list(rec(data)) # [1, 2, 3, 4, 5, 6, 7] 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -