user3313834 user3313834 - 1 year ago 92
Python Question

Filter inner keys from 2 level nested dictionaries

I looking the most elegant way to get this:

{'i_1': {'a': 33, 't': 4}, 'i_2': {'a': 9, 't': 0}}

From this:

{'i_1': {'a': 33, 'b': 55, 't': 4}, 'i_2': {'a': 9, 'b': 11, 't': 0}}

Each inner dict can have a lot of a, b, ..., z keys.

for now I have this::

In [3]: {k:dict(a=d[k]['a'], t=d[k]['t']) for k in d.keys()}
Out[3]: {'i_1': {'a': 33, 't': 4}, 'i_2': {'a': 9, 't': 0}}

but it's not very elegant

Answer Source

You can make your code a little bit more readable by using items instead of keys:

{k: dict(a=v['a'], t=v['t']) for k, v in d.items())