473,609 Members | 2,222 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

modify dictionary while iterating

hi
I wish to pop/del some items out of dictionary while iterating over it.
a = { 'a':1, 'b':2 }
for k, v in a.iteritems():
if v==2:
del a[k]

the output say RuntimeError: dictionary changed size during iteration
how can i suppress this message in an actual script and still get the
final value of the dict?
is it something like try/except/else statment?
try:
for v,k in a.iteritems():
if v==something:
del a[k]
except RuntimeError:
< don't know what to do here>
else:
< should i include this part ? >

what other ways can i do this ? thanks for any help.

Nov 11 '05 #1
5 8788
s9************@ yahoo.com wrote:
hi
I wish to pop/del some items out of dictionary while iterating over it.
a = { 'a':1, 'b':2 }
for k, v in a.iteritems():
if v==2:
del a[k]

the output say RuntimeError: dictionary changed size during iteration
how can i suppress this message in an actual script and still get the
final value of the dict?
is it something like try/except/else statment?
try:
for v,k in a.iteritems():
if v==something:
del a[k]
except RuntimeError:
< don't know what to do here>
else:
< should i include this part ? >

what other ways can i do this ? thanks for any help.


If you expect to delete only a few items:
a = dict(a=1, b=2, c=3, d=2)
delenda = [k for k, v in a.iteritems() if v == 2]
for k in delenda: .... del a[k]
.... a {'a': 1, 'c': 3}

If you expect to delete most items:
a = dict(a=1, b=2, c=3, d=2)
a = dict((k, v) for k, v in a.iteritems() if v != 2)
a {'a': 1, 'c': 3}

or (if rebinding a is not an option)
a = dict(a=1, b=2, c=3, d=2)
for k, v in a.items(): .... if v == 2:
.... del a[k]
.... a

{'a': 1, 'c': 3}

Peter

Nov 11 '05 #2
s9************@ yahoo.com wrote:
I wish to pop/del some items out of dictionary while iterating over
it.


Iterate over a copy.

a_orig = { 'a': 1, 'b': 2 }
a = dict(a_orig)
for k, v in a_orig.iteritem s():
if v == 2:
del a[k]

--
\ "I know the guy who writes all those bumper stickers. He hates |
`\ New York." -- Steven Wright |
_o__) |
Ben Finney
Nov 11 '05 #3
Iterate over the keys.... ( for entry in adict.keys(): )

All the best,

Fuzzy
http://www.voidspace.org.uk/python/index.shtml

Nov 11 '05 #4
>> I wish to pop/del some items out of dictionary while iterating over
it.


Ben> Iterate over a copy.

Ben> a_orig = { 'a': 1, 'b': 2 }
Ben> a = dict(a_orig)
Ben> for k, v in a_orig.iteritem s():
Ben> if v == 2:
Ben> del a[k]

Or iterate over just a copy of the keys:

for k in a_orig.keys():
if a_orig[k] == 2:
del a_orig[k]

Skip
Nov 11 '05 #5
[s9************@ yahoo.com]
I wish to pop/del some items out of dictionary while iterating over it. a = { 'a':1, 'b':2 }
for k, v in a.iteritems():
if v==2:
del a[k]


A simple change would be using "items()" instead of "iteritems( )".

Or else, you may prefer to loop over keys, and retrieve values, either:

for k in a.keys():
if a[k] == 2:
del a[k]

or:

for k in set(a):
if a[k] == 2:
del a[k]

But in no way, you may directly iterate over the original dictionary
while altering its keys, this is explicitly forbidden in Python.

--
François Pinard http://pinard.progiciels-bpi.ca
Nov 11 '05 #6

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

Similar topics

4
3640
by: Julian Yap | last post by:
Hi all, I'm trying to get some ideas on the best way to do this. In this particular coding snippet, I was thinking of creating a dictionary of file objects and file names. These would be optional files that I could open and parse. At the end, I would easily close off the files by iterating through the dictionary. ---< CODE FOLLOWS >--- optionalfiles = {fileAreaCode: "areacode.11", fileBuild: "build.11"}
4
6164
by: Martin Widmer | last post by:
Hi folks. I am using this collection class: Public Class ContentBlocksCollection Inherits DictionaryBase 'Object variables for attributes 'Attributes Default Public Property Item(ByVal nDBKey As Long) As ContentBlock Get
1
4502
by: Martin Widmer | last post by:
Hi Folks. When I iterate through my custom designed collection, I always get the error: "Unable to cast object of type 'System.Collections.DictionaryEntry' to type 'ContentObjects.ContentBlock'." The error occurs at the "For...Each" line if this method:
6
46169
by: buzzweetman | last post by:
Many times I have a Dictionary<string, SomeTypeand need to get the list of keys out of it as a List<string>, to pass to a another method that expects a List<string>. I often do the following: <BEGIN CODE> List<stringkeyNameList = new List<string>(); foreach (string keyName in this.myDictionary.Keys)
4
34150
by: O.B. | last post by:
I need the ability to parse through the values of a Dictionary and remove certain ones depending on their attribute values. In the example below, an InvalidOperationException is thrown in the foreach statement when the first item is removed from the Dictionary. From looking at Dictionary's methods, I couldn't find anything to create a copy of the Values before starting the foreach loop. Help? static void someTest() {
0
2345
by: Jon Slaughter | last post by:
How do I modify the value of a dictionary object? I have something like Dictionary<string, AQ = ... Where A is a struct. I want to change some values in A but
8
7970
by: Bob Altman | last post by:
Hi all, I'm trying to do something that should be really easy, but I can't think of an obvious way to do it. I have a dictionary whose value is a "value type" (as opposed to a reference type -- in this case, a Boolean): Dim dic As New Dictionary(Of Int32, Boolean) dic(123) = True I want to set all of the existing entries in the dictionary to False. The
10
1975
by: ++imanshu | last post by:
Hi, Wouldn't it be nicer to have 'in' return values (or keys) for both arrays and dictionaries. Arrays and Dictionaries looked so similar in Python until I learned this difference. Thanks, ++imanshu
2
10985
by: mmiikkee13 | last post by:
>>a_list = range(37) .... print k, v .... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'int' object is not iterable What 'int' object is this referring to? I'm iterating over a dict, not an int.
0
8115
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 usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8053
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 synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8513
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
8205
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
4007
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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4066
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2519
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
1
1638
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1374
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 effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.