Shankar Cabus
Shankar Cabus

Reputation: 9792

Traverse a dictionary recursively in Python?

What is the better way to traverse a dictionary recursively? Can I do it with 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]

Upvotes: 1

Views: 2633

Answers (4)

erdogant
erdogant

Reputation: 1694

The dicter library can be useful. You can easily flatten or traverse the dictionary paths.

pip install dicter

import dicter as dt

# Example dict:
d = {'level_a': 1, 'level_b': {'a': 'hello world'}, 'level_c': 3, 'level_d': {'a': 1, 'b': 2, 'c': {'e': 10}}, 'level_e': 2}

# Walk through dict to get all paths
paths = dt.path(d)

print(paths)
# [[['level_a'], 1],
# [['level_c'],  3],
# [['level_e'], 2],
# [['level_b', 'a'], 'hello world'],
# [['level_d', 'a'], 1],
# [['level_d', 'b'], 2],
# [['level_d', 'c', 'e'], 10]]

The first column is the key path. The 2nd column are the values. In your case, you can take in the 1st column all last elements.

Upvotes: 0

sinceq
sinceq

Reputation: 924

My solution:

results = []
def function(lst):
    for item in lst:
        results.append(item.get('id'))
        function(item.get('children'))
function(l)
print results

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

Upvotes: 0

Rob Watts
Rob Watts

Reputation: 7146

The easiest way to do this will be with a recursive function:

recursive_function = lambda x: [x['id']] + [item for child in x['children'] for item in recursive_function(child)]
result = [item for topnode in whatever_your_list_is_called for item in recursive_function(topnode)]

Upvotes: 3

thefourtheye
thefourtheye

Reputation: 239693

You can recursively traverse your dictionaries, with this generic generator function, like this

def rec(current_object):
    if isinstance(current_object, dict):
        yield current_object["id"]
        for item in rec(current_object["children"]):
            yield item
    elif isinstance(current_object, list):
        for items in current_object:
            for item in rec(items):
                yield item

print list(rec(data))
# [1, 2, 3, 4, 5, 6, 7]

Upvotes: 3

Related Questions