python - How to remove a value but keep the corresponding key in a dictionary? -
suppose have dictionary:
d1 = {'a1' : [2, 3], 'b1': [3, 3], 'c1' : [4, 5]}
and wanted remove 3
s d1
get:
d1 = {'a1' : [2], 'b1': [], 'c1' : [4, 5]}
something works, assuming 3 appears in value, not in key
>>> v in d1.values(): ... if 3 in v: ... v.remove(3) ... >>> d1 {'a1': [2], 'c1': [4, 5], 'b1': [3]}
edit: realized can multiple occurence, try one
>>> d1 = {'a1' : [2, 3], 'b1': [3, 3], 'c1' : [4, 5]} >>> k, v in d1.items(): ... d1[k] = filter(lambda x: x!=3, v) ... >>> d1 {'a1': [2], 'c1': [4, 5], 'b1': []}
Comments
Post a Comment