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).

JavaScript

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:

JavaScript

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:

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement