Skip to content
Advertisement

Filter nested dictionary in Python

I’m trying to remove key: value pairs from a nested dictionary within a nested dictionary, based on the value of a value within the double-nested dict.

The dictionary looks something like this, and I want to filter out entire entries of people with an age under 25 years old (while I do not want to filter out the outermost dictionary, so the “people group” one).

# Make a nested dictionary for test
people = {0:{1:{'name': 'John', 'age': '27', 'gender': 'Male'},
          2: {'name': 'Marie', 'age': '22', 'gender': 'Female'},
          3: {'name': 'Nicola', 'age': '19', 'gender': 'Non-binary'},
          4: {'name': 'Garfield', 'age': '32', 'gender': 'Male'}},
         1:{1:{'name': 'Katie', 'age': '24', 'gender': 'Male'},
          2: {'name': 'Marigold', 'age': '42', 'gender': 'Female'},
          3: {'name': 'James', 'age': '10', 'gender': 'Non-binary'},
          4: {'name': 'Precious', 'age': '35', 'gender': 'Male'}}}

I have found my way to this thread, which is somewhat similar, although there’s only one layer of “nestedness” there.

From it, I learnt that I could do something like this to filter keys with too low values tied to them, if my dictionary had only been nested one round:

{i:j for i,j in people.items() if j.get('age',0) >='25'}

How can I reach the element within a double-nested dictionary like this, and then remove the whole “single-nested dictionary”, but keep the outermost one?

Advertisement

Answer

You can use nested dict comprehension:

>>> {gid: {uid: user for uid, user in pg.items() if int(user.get('age', 0)) >= 25} for gid, pg in people.items()}
{0: {1: {'name': 'John', 'age': '27', 'gender': 'Male'},
  4: {'name': 'Garfield', 'age': '32', 'gender': 'Male'}},
 1: {2: {'name': 'Marigold', 'age': '42', 'gender': 'Female'},
  4: {'name': 'Precious', 'age': '35', 'gender': 'Male'}}}
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement