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

ranjan das ranjand2005 at gmail.com
Fri Apr 1 09:52:17 CEST 2011


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

reject_list=[]

for element in B:

    for key in A.keys():

        for i in range(len(A[key])):

            if element==A[key][i]:

                reject_list.append((key,A[key][i]))



print reject_list


for i in range(len(reject_list)):

    print (reject_list[i][0],reject_list[i][1])

    Index=A[reject_list[i][0]].index(reject_list[i][1])

    print (reject_list[i][0],reject_list[i][1],Index)

    del A[reject_list[i][0]][Index]


print A


result obtained:

{'g2': [4], 'g1': [1]}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110401/7c90c8c8/attachment.html>


More information about the Tutor mailing list