Python 2.7 Improve algorithm that checks if a dictionary key is not in a list and if so deletes that key
<p>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: </p>

<pre><code>d = {1 : "bob", 2 : "mary", 3 : "joe"}
l = [2,3]
</code></pre>

<p>The first key of d gets deleted.</p>

<pre><code>d = {2 : "mary", 3 : "joe"}
l = [2,3]
</code></pre>

<p>I have a working solution but feel the use of flags is unnecessary. </p>

<pre><code>flag = False
del_vals = list()

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

for k in del_vals: 
  d.pop(k, None)
</code></pre>

<p>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. </p>

<p>You can also use sets for achieving the same:</p>

<pre><code>z={i:d[i] for i in set(d.keys()).intersection(l)}
</code></pre>

<p>or use the below</p>

<pre><code>p={i:d[i] for i in d.keys() if i in l}
</code></pre>

<p>or do this</p>

<pre><code>q={i:d[i] for i in set(d.keys()) &amp; set(l)}
</code></pre>

<p>Alternatively, you could do this as well:</p>

<pre><code>for i in set(d.keys()) - set(l):
    del(d[i])
</code></pre>

python python-2.7 dictionary