Yunti
Yunti

Reputation: 7428

Strip nested dict of non zero values

I'm trying to strip a nested dict (only 1 level deep eg: some_dict = {'a':{}, b:{}} all all non-zero and none values.
However I'm not sure who to reassemble the dict properly, the below gives me a key error.

def strip_nested_dict(self, some_dict):
    new_dict = {}
    for sub_dict_key, sub_dict in some_dict.items():
        for key, value in sub_dict.items():
            if value:
                new_dict[sub_dict_key][key] = value
    return new_dict

Upvotes: 1

Views: 169

Answers (2)

Yunti
Yunti

Reputation: 7428

This worked. Shame you can't just assign a nested value without having to create an empty for for each key first.

def strip_nested_dict(self, some_dict):
    new_dict = {}
    for sub_dict_key, sub_dict in some_dict.items():
        new_dict[sub_dict_key] = {}
        for key, value in sub_dict.items():
            if value:
                new_dict[sub_dict_key][key] = value
    return new_dict

Upvotes: 0

Mohammed Aouf Zouag
Mohammed Aouf Zouag

Reputation: 17132

You need to create the nested dictionary before accessing it:

for sub_dict_key, sub_dict in some_dict.items():
    new_dict[sub_dict_key] = {} # Add this line

    for key, value in sub_dict.items():
        # no changes

(In order for new_dict[sub_dict_key][key] to work, new_dict must be a dictionary, & new_dict[sub_dict_key] also has to be a dictionary.)

Upvotes: 1

Related Questions