[Tutor] Removing values from a dictionary if they are present in a list

Peter Otten __peter__ at web.de
Fri Apr 1 10:11:44 CEST 2011


ranjan das wrote:

> I have the following information
> 
> A={'g2': [4,5,3], 'g1': [1, 3]}
> 
> B=[2,3,5]
> 
> Now I want to remeove the elements in B if they are present (as values) in
> dictionary A.
> 
> My expected solution is
> 
> A= {'g2': [4], 'g1': [1] }
> 
> I wrote the following piece of code which gives me thhe right code, but I
> am sure there must be a much shorter and more elegant way of doing it.
> Please suggest

The following is a bit shorter, but not really elegant:

>>> a = {'g2': [4, 5, 3], 'g1': [1, 3]}
>>> b = [2, 3, 5]
>>> for v in a.itervalues():
...     v[:] = [item for item in v if item not in b]
...
>>> a
{'g2': [4], 'g1': [1]}

If you are free to choose your data types use sets instead of lists:

>>> a = {'g2': set([4, 5, 3]), 'g1': set([1, 3])}
>>> b = set([2, 3, 5])
>>> for v in a.itervalues():
...     v -= b
...
>>> a
{'g2': set([4]), 'g1': set([1])}




More information about the Tutor mailing list