BDillan BDillan - 5 months ago 26
Python Question

Python 2.7 Improve algorithm that checks if a dictionary key is not in a list and if so deletes that key

I was playing around with a few solutions but am looking for an optimal and clean way to do this in Python. Basically I have a dictionary called 'd', and a list 'l'. If the dictionary contains a value not in the list delete that value in the dictionary. So given:

d = {1 : "bob", 2 : "mary", 3 : "joe"}
l = [2,3]

The first key of d gets deleted.

d = {2 : "mary", 3 : "joe"}
l = [2,3]

I have a working solution but feel the use of flags is unnecessary.

flag = False
del_vals = list()

for key in d.iterkeys():
for i in l:
if key == i: flag = True
if flag == False:
flag = False

for k in del_vals:
d.pop(k, None)

Is there a way I can write it to improve performance and make it more clean? Whether the use of generators or anything else is involved.


A list comprehension will work starting from Python 2.7:

d = {k: v for k, v in d.iteritems() if k in l}

Use items() instead of iteritems() in Python 3:

d = {k: v for k, v in d.items() if k in l}