473,569 Members | 2,648 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Removing dictionary-keys not in a set?

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

Jul 19 '05 #1
9 3290
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

Jul 19 '05 #2
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]


You could try a generator expression:

py> d = {1: 2, 3: 4, 5: 6, 7: 8, 9: 10}
py> s = set([1, 5, 7])
py> dict((k, v) for k, v in d.iteritems() if k in s)
{1: 2, 5: 6, 7: 8}

Note that your variation 2 won't work:

py> for key in d.iterkeys():
.... if key not in s:
.... del d[key]
....
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
RuntimeError: dictionary changed size during iteration

You can make it work using keys() instead of iterkeys():

py> for key in d.keys():
.... if key not in s:
.... del d[key]
....
py> d
{1: 2, 5: 6, 7: 8}

But I think I'd probably lean towards the generator expression...

STeVe
Jul 19 '05 #3
In article <11************ **********@l41g 2000cwc.googleg roups.com>,
Tim N. van der Leeuw <ti************ *@nl.unisys.com > 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.


Why not just use the builtin set operations?
--
Aahz (aa**@pythoncra ft.com) <*> http://www.pythoncraft.com/

"The joy of coding Python should be in seeing short, concise, readable
classes that express a lot of action in a small amount of clear code --
not in reams of trivial code that bores the reader to death." --GvR
Jul 19 '05 #4
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@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@home:~ $

#v-

--
Klaus Alexander Seistrup
Magnetic Ink, Copenhagen, Denmark
http://magnetic-ink.dk/
Jul 19 '05 #5
Hi Aahz,

The problem with using the builtin set operations is, that the
dictionary keys don't represent a set, so you can't directly create a
new dictionary using set methods.

So I'm looking for what's a concise way to update a dictionary, or
create a new dictionary, using basically an intersection method.

(I'm using Python 2.4.1 so I do have convenient builtin set operations
available)

In my taste, using generator expressions with conditions actually
doesn't look very readable; it hides the set-membership test under the
syntactic clutter.
(I don't mind generator expressions in principle, but I do feel that
here they clutter up the intent of the code)

cheers,

--Tim

Jul 19 '05 #6
Hi Klaus,

I think I like the looks of your version the best, so far. Readable and
clear, to me.

cheers and thanks,

--Tim

Jul 19 '05 #7
Tim N. van der Leeuw wrote:
In my taste, using generator expressions with conditions actually
doesn't look very readable; it hides the set-membership test under the
syntactic clutter.


You might try different indentation. I find that I write a lot of my
list comprehensions and generator expressions like:

dict((k, v)
for k, v in d.iteritems()
if k in s)

It looks much more like the for-loop in my mind, and I can easily spot
each of the for- and if-expressions in the genexp.

STeVe
Jul 19 '05 #8
"Tim N. van der Leeuw" <ti************ *@nl.unisys.com > wrote in message news:<11******* *************** @l41g2000cwc.go oglegroups.com> ...
Hi,

I'd like to remove keys from a dictionary, which are not found in a
specific set.


Here's my magic English-to-Python translator:

"I'd like to ... keys which ..." -> "for key in"
"keys from a dictionary" -> "set(dictionary )"
"not found in a specific set" -> "-specificset"
"... remove keys ..." -> "del dictionary[key]"

Putting it all together:
for key in set(dictionary)-specificset:

.... del dictionary[key]

Oren
Jul 19 '05 #9
[Klaus Alexander Seistrup]
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]
...


FWIW, if s2 is not already a set object, it need not be transformed before using
it. Instead, write:

for k in set(d1).differe nce([1,3,5]):
del d1[k]

If you prefer to work with dictionaries instead of sets, then adapt the existing
code for symmetric_diffe rence_update() in sets.py.

Raymond Hettinger
Jul 19 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
16970
by: JohnK | last post by:
ok, ya got me here. I'm trying to removing items from a dictionary inside a loop. Obviously using enumeration does not work as that assumes the dictionary stays unchanged. So how so I iterate through a dictionary, looking for things, then remove them.... John
0
1197
by: Miguel Cruz | last post by:
Is it possible to select an alternate master dictionary when using the pspell interface? There is a way to select a personal dictionary (pspell_config_personal()), but that is used IN ADDITION to the default master dictionary, which is not what I want. I have a different English dictionary I wish to use, and I do not want to use the default...
6
23255
by: JD | last post by:
Hello, I try to remove a dictionary key-pair (remove an entry), but I'm unsuccessful. Does anyone know how to achieve this? Thanks
4
14684
by: NullQwerty | last post by:
Hi folks, I have a Dictionary which contains a string key and an object value. I want the object value to point to a property in my class and I want it to be by reference, so that later on I can change the value of the property through the dictionary. I am having difficulty making the value be by reference. Is this possible? I've even...
70
27347
by: jojoba | last post by:
Hello! Does anyone know how to find the name of a python data type. Conside a dictionary: Banana = {} Then, how do i ask python for a string representing the name of the above dictionary (i.e. 'Banana')?
17
2692
by: Eric_Dexter | last post by:
def simplecsdtoorc(filename): file = open(filename,"r") alllines = file.read_until("</CsInstruments>") pattern1 = re.compile("</") orcfilename = filename + "orc" for line in alllines: if not pattern1 print >>orcfilename, line I am pretty sure my code isn't close to what I want. I need to be able
13
3028
by: jerger | last post by:
my program takes users input (words/sentance) and translates it from english to hmong. I have to main variables, but cannot post my entire code. char In; CString in; basically the user cin >> In; then later in = In, then computes using the dictionary. is there anyway i can remove ! commas and periods from the input before translating in...
3
2787
by: Stef Mientki | last post by:
hello, I want to remove some items from a dictionary, so I would expect this should work: Nets = {} ... fill the dictionary Nets for net in Nets: if net.upper() in Eagle_Power_Nets :
3
13692
by: Al Meadows | last post by:
I'm using a generic Dictionary object where it is described as: Dictionary<this, thatstuff = new Dictonary<this, that>() Where THIS is a class with several property values. This works fine as far as adding the key/value pairs to the dictionary. The problem is when I contruct a new THIS object:
1
2215
by: Manikrag | last post by:
Please help as this issue is driving us crazy... Any idea would be of great help.. Application is running over IIS and I am getting error " Index was outside the bounds of the array." on the Session_Start on line AllSessions = GetSession.GetNewSession(Context); When I tried to catch the error I got random values for AllSessions.Count....
0
7701
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7615
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
0
7924
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7979
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
6284
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
0
5219
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3653
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
1
1223
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
940
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.