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

Steven D'Aprano steve at pearwood.info
Fri Apr 1 14:12:06 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] }


Do you care about the order of the elements in A's values? Will there be 
any duplicate values?

If the answer is No to both of those, the simplest solution is probably 
this:

b = set(B)
for key, values in A.items():
     A[key] = list( set(values).difference(b) )


For Python 3, you will need to change the call A.items() to 
list(A.items()), but otherwise they should be the same.

If you do care about order and duplicates, then this should do it:


# untested
for key, values in A.items():
     A[key] = [x for x in values if x not in B]


Not the most efficient code in the universe, but for small lists (say, a 
few hundred items) it should be perfectly fine.


-- 
Steven



More information about the Tutor mailing list