Removing dictionary-keys not in a set?

Klaus Alexander Seistrup klaus at seistrup.dk
Mon Apr 18 13:24:05 EDT 2005


Tim N. van der Leeuw wrote:

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

How about

#v+

klaus at home:~ $ python
Python 2.4.1 (#2, Mar 30 2005, 21:51:10)
[GCC 3.3.5 (Debian 1:3.3.5-8ubuntu2)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> d1 = {1:'a', 2:'b', 3:'c', 4:'d', 5:'e'}
>>> s1 = set(d1)
>>> s1
set([1, 2, 3, 4, 5])
>>> s2 = set([1, 3, 5])
>>> s1-s2
set([2, 4])
>>> for k in s1-s2:
...     del d1[k]
... 
>>> d1
{1: 'a', 3: 'c', 5: 'e'}
>>> ^D
klaus at home:~ $ 

#v-

-- 
Klaus Alexander Seistrup
Magnetic Ink, Copenhagen, Denmark
http://magnetic-ink.dk/



More information about the Python-list mailing list