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 3s 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

Popular posts from this blog

html5 - What is breaking my page when printing? -

c# - must be a non-abstract type with a public parameterless constructor in redis -

ajax - PHP/JSON Login script (Twitter style) not setting sessions -