LegendWK
LegendWK

Reputation: 194

Remove values from nested dictionary

I've got a nested dictionary:

{'a': {'m': 1, 'n': 0}, 'b': {'m': 0, 'x': 1}}

is there a simple way of removing all the nested zero values so the dictionary becomes:

{'a': {'m': 1}, 'b': {'x': 1}}

Upvotes: 2

Views: 80

Answers (6)

R. Baraiya
R. Baraiya

Reputation: 1530

You can even try to convert your nested dict to flat and then look for value zero

Code:

[d[k[0]].pop(k[-1]) for k,v in pd.json_normalize(d).to_dict(orient='records')[0].items() if v==0]
d

Upvotes: 0

vipul prajapati
vipul prajapati

Reputation: 1

dict_1 = {'a': {'m': 1, 'n': 0}, 'b': {'m': 0, 'x': 1}}
new_dict_1={}
for key in dict_1.keys():
    for v,k in zip(dict_1[key].values(),dict_1[key].keys()):
        if v != 0 :
            new_dict_1[key] = {k:v}
            
new_dict_1

Upvotes: 0

Dani Mesejo
Dani Mesejo

Reputation: 61900

One approach, that modifies the dictionary in-place:

d = {'a': {'m': 1, 'n': 0}, 'b': {'m': 0, 'x': 1}}

for dd in d.values():
    for k, v in list(dd.items()):
        if v == 0:
            dd.pop(k)

print(d)

Output

{'a': {'m': 1}, 'b': {'x': 1}}

Upvotes: 2

Piano Tutorials
Piano Tutorials

Reputation: 1

One-line solution:

d = {'a': {'m': 1, 'n': 0}, 'b': {'m': 0, 'x': 1}}

d_new = {k: {inner_k: inner_v for inner_k, inner_v in v.items() if inner_v != 0} for k, v in d.items()}

print(d_new)  # Prints: {'a': {'m': 1}, 'b': {'x': 1}}

Upvotes: 0

dimnnv
dimnnv

Reputation: 814

You can use dict comprehension:

d = {'a': {'m': 1, 'n': 0}, 'b': {'m': 0, 'x': 1}}
result = {k: {k1: v1 for k1, v1 in v.items() if v1 != 0} for k, v in d.items()}

Upvotes: 0

LegendWK
LegendWK

Reputation: 194

Dictionary comprehension:

>>> d = {'a': {'m': 1, 'n': 0}, 'b': {'m': 0, 'x': 1}}
>>> {key: {k:v for k,v in d[key].items() if v != 0} for key in d}

Output:

{'a': {'m': 1}, 'b': {'x': 1}}

Upvotes: 2

Related Questions