I have a dictionary of dictionary as below how to remove non zero key,values from this
{'abcdef': {'1987': 0.0,
'0544': 0.0,
'0568': 0.0,
'3000': 0.0,
'7095': 0.0,
'75609': 1.0,
'56565': 2.0,
'98656': 3.0,
'756095': 0.0,
'23432': 0.0},
'fgrd': {'1987': 0.0,
'0544': 0.0,
'0568': 0.0,
'3000': 0.0,
'7095': 0.0,
'75609': 1.0,
'56565': 2.0,
'98656': 3.0,
'756095': 0.0,
'23432': 0.0}
}
Tried below, {key:val for key, val in my_dict.items() if val.values() != 0.0}
and getting AttributeError: 'float' object has no attribute 'values',
Thanks
CodePudding user response:
Try this:
dct = {'abcdef': {'1987': 0.0,
'0544': 0.0,
'0568': 0.0,
'3000': 0.0,
'7095': 0.0,
'75609': 1.0,
'56565': 2.0,
'98656': 3.0,
'756095': 0.0,
'23432': 0.0},
'fgrd': {'1987': 0.0,
'0544': 0.0,
'0568': 0.0,
'3000': 0.0,
'7095': 0.0,
'75609': 1.0,
'56565': 2.0,
'98656': 3.0,
'756095': 0.0,
'23432': 0.0},
'xyz':0.0,
}
out = {}
for k,v in dct.items():
if isinstance(v, dict):
out[k] = {k2:v2 for k2,v2 in v.items() if v2==0}
else:
out[k] = v
print(out)
Output:
{'abcdef': {'1987': 0.0, '0544': 0.0, '0568': 0.0, '3000': 0.0, '7095': 0.0, '756095': 0.0, '23432': 0.0},
'fgrd': {'1987': 0.0, '0544': 0.0, '0568': 0.0, '3000': 0.0, '7095': 0.0, '756095': 0.0, '23432': 0.0},
'xyz': 0.0}
CodePudding user response:
you have to iterate over the primary dictionary and than look for values in secondary dict here is an example:
val = {'abcdef': {'1987': 0.0,
'0544': 0.0,
'0568': 0.0,
'3000': 0.0,
'7095': 0.0,
'75609': 1.0,
'56565': 2.0,
'98656': 3.0,
'756095': 0.0,
'23432': 0.0}}
for dict_k in val:
for dicts in val.values():
for k in dicts.copy():
if dicts[k] != 0.0:
dicts.pop(k)
print(val)