Reputation: 194
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
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
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
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
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
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
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