user3313834
user3313834

Reputation: 7837

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

Upvotes: 3

Views: 511

Answers (3)

Absolut
Absolut

Reputation: 1310

import copy

def foo(d):
    d_copy = copy.deepcopy(d)

    for key in d_copy:
        print(key, d[key])
        if isinstance(d[key], dict):
            foo(d[key])
        if key == 'b':
            d.pop(key)

Upvotes: 0

GingerPlusPlus
GingerPlusPlus

Reputation: 5636

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

Upvotes: 2

Jezor
Jezor

Reputation: 3426

Here you go. This functions takes a dict in a format you specified and a list of keys that have to be removed from inner dictionaries:

def remove_inner_keys(data: dict, inner_keys_to_remove: list) -> dict:
    result = dict()

    for outer_key in data.keys():
        partial_result = dict()
        for inner_key in data[outer_key]:
            if inner_key not in inner_keys_to_remove:
                partial_result[inner_key] = data[outer_key][inner_key]
        result[outer_key] = partial_result

    return result

Testing:

data = { 'i_1': { 'a': 33, 'b': 55, 't': 4 }, 'i_2': { 'a': 9, 'b': 11, 't': 0 } }
print(str(remove_inner_keys(data, ["b"])))

output:

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

Upvotes: 0

Related Questions