Archimeow
Archimeow

Reputation: 240

Filtering out keys the are not shared between two nested dictionaries

I'm a newbie to python, so please bear with me as I learn.

I have two defaultdicts, one with nested values:

d1 = defaultdict(dd_list)
d1 = {'a': {'b1': 12, 'c21': 41}, 'ff': {'h1': 2, 'b1': 32}}

d2 = defaultdict(dd_list)
d2 = {'a': 22, 'b1': 77, 'g8': 10, 'h1': 37}

I would like to filter d1 to return just the key-value pairs for the keys that are present in d2:

 {'a': {'b1': 12}, 'ff': {'b1': 32, 'h1': 2}}

I tried using the approach described here but was unable to adapt it to this situation.

Thank you in advance!

Upvotes: 1

Views: 56

Answers (1)

alecxe
alecxe

Reputation: 474071

You can solve it with a nested dictionary comprehension:

>>> d1 = {'a': {'b1': 12, 'c21': 41}, 'ff': {'h1': 2, 'b1': 32}}
>>> d2 = {'a': 22, 'b1': 77, 'g8': 10, 'h1': 37}
>>> 
>>> print({key: {inner_key: inner_value for inner_key, inner_value in value.items() if inner_key in d2}
...        for key, value in d1.items()})
{'a': {'b1': 12}, 'ff': {'h1': 2, 'b1': 32}}

In this state though, the solution does not scale for an arbitrary nestedness level.

Upvotes: 1

Related Questions