python - Filtering out keys the are not shared between two nested dictionaries -


i'm newbie python, please bear me learn.

i have 2 defaultdicts, 1 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 filter d1 return key-value pairs keys present in d2:

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

i tried using approach described here unable adapt situation.

thank in advance!

you can solve 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 inner_key, inner_value in value.items() if inner_key in d2} ...        key, value in d1.items()}) {'a': {'b1': 12}, 'ff': {'h1': 2, 'b1': 32}} 

in state though, solution not scale arbitrary nestedness level.


Comments

Popular posts from this blog

Django REST Framework perform_create: You cannot call `.save()` after accessing `serializer.data` -

Why does Go error when trying to marshal this JSON? -