Removing dictionary-keys not in a set?

Satchidanand Haridas sharidas at zeomega.com
Mon Apr 18 08:43:16 EDT 2005


Hi,

I am not sure if this way is a good one, but it certainly is consise. 
Also sometimes, it's better to go for a simple approach than the consise 
one (for readability). With the abive disclaimer, I present my solution:

d1 = {1 : 2, 3 : 4, 5 : 6, 7 : 8, 9 : 10 }
s1 = [ 1, 5, 7 ]

# assuming you are using python 2.3.5
import sets
d2 = dict( [ ( x, d1[ x ] ) for x in sets.Set( d1.keys() ). 
intersection( sets.Set( s1 ) ) ] )


thanks,
Satchit


Tim N. van der Leeuw wrote:

>Hi,
>
>I'd like to remove keys from a dictionary, which are not found in a
>specific set. So it's kind of an intersection-operation.
>
>I can create a new dictionary, or a loop over all keys and test them
>for set-membership, but I was wondering if there was a smart way to
>express this in 1 or 2 concise statements that I'm not aware of.
>
>So are there smarter ways to get the intersection of dictionary and set
>into a dictionary than the following pseudo-code:
>
># Variation 1
>d2 = {}
>for key in s: d2[key] = d1[key]
>
># Variation 2
>for key in d.iterkeys(): if key not in s: del d[key]
>
>
>And if there's no smarter way, then which of these two options would
>give best performance?
>
>Cheers,
>
>--Tim
>
>  
>



More information about the Python-list mailing list