473,396 Members | 2,030 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

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 8770
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.iteritems():
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.iteritems():
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
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...
4
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...
1
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...
6
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: ...
4
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...
0
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
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 --...
10
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,...
2
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...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
0
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...
0
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...
0
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...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

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.