Ali Khosro
Ali Khosro

Reputation: 1830

subset a nested dictionary

nested = {'a':{'aa':1, 'bb':2}, 'b':{'aa':3, 'bb':4}}

How to get the result as a subset of nested where the second key is 'aa':

result = {'a':{'aa':1}, 'b':{'aa':3}}

I tried this one but did not work:

result = {k1:{k2:nested[k1][k2]} for k1 in nested.keys() & k2 in ['aa']}

Thank you in advance.

Upvotes: 1

Views: 2107

Answers (1)

akuiper
akuiper

Reputation: 215137

You can use a nested dictionary comprehension with a filter for the inner dict, (this will create a new dictionary instead of modifying the original one):

{k1: {k2: v2 for k2, v2 in v1.items() if k2 == 'aa'} for k1, v1 in nested.items()}
# {'a': {'aa': 1}, 'b': {'aa': 3}}

Upvotes: 5

Related Questions