Paul Noon
Paul Noon

Reputation: 686

Retrieve list of values from nested dictionaries

I am working with Python 2.7.

I have the following list:

mylist = [
       {u'id': 5650,
               u'children': [
                     {u'id': 4635},
                     {u'id': 5648}
                            ]},
       {u'id': 67,
               u'children': [
                     {u'id': 77}
                            ]}
      ]

I would like to retrieve the list of all children ids:

[4635, 5648, 77]

I have tried:

childrenids = [elem['children'][0]['id'] for elem in mylist]

but this only gives me the first one of each children:

[4635, 77]

I cannot manage to get all of them.

Any clue?

Upvotes: 1

Views: 2438

Answers (2)

BiancaO
BiancaO

Reputation: 1

My solution iterates through the elements of the list (assuming that each element is a valid dictionary) and checks the type of each element based on the 'id' and 'children' naming convention.

def extract_id_values(mylist):
  ids_to_return_list = []

  for element in mylist:
      for key, value in element.items():
          if 'id' == key:
            ids_to_return_list.append(value)
          if 'children' == key:
            for children_elem in value:
              if 'id' in children_elem:
                ids_to_return_list.append(children_elem['id'])
  return ids_to_return_list

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81604

childrenids = [elem['children'][0]['id'] for elem in mylist]

Why the [0]? This will only grab the value of the first child.

Instead try childrenids = [child['id'] for elem in mylist for child in elem['children']].

Upvotes: 4

Related Questions