Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #7976

Re: How to iterate on a changing dictionary

From Terry Reedy <tjreedy@udel.edu>
Subject Re: How to iterate on a changing dictionary
Date 2011-06-19 12:02 -0400
References <itl1a5$rom$1@speranza.aioe.org> <BANLkTik=OXt0X9g=ashkhc3o_Dv_UM=MCA@mail.gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.157.1308499346.1164.python-list@python.org> (permalink)

Show all headers | View raw


On 6/19/2011 11:13 AM, Chris Angelico wrote:
> On Mon, Jun 20, 2011 at 12:32 AM, TheSaint<nobody@nowhere.net.no>  wrote:
>> Hello
>>
>> Trying to pop some key from a dict while is iterating over it will cause an
>> exception.
>> How I can remove items when the search result is true.
>>
>> Example:
>>
>> while len(dict):
>>    for key in dict.keys():
>>       if dict[key] is not my_result:
>>          dict.pop(key)
>>     else:
>>        condition_to_break
>> print('Dictionary is over')
>
> One way is to iterate over an explicitly formed list of the keys.
>
> for key in list(dict.keys()):
>
> That creates an entirely new list with a snapshot copy of the keys. If
> you then remove elements from the dictionary, the list will still
> iterate correctly.

The other is to make a set of to_be_deleted keys and delete them all 
when done.

If you only want to delete one key, break the iteration and then delete.

> I'm not sure what you're trying to do,  but you may find it easier to
> use the 'filter' function (which takes an iterable, so possibly use
> dict.iteritems() for that).It'll keep some and not others, and then
> you can make use of just the ones you get back.



-- 
Terry Jan Reedy

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

How to iterate on a changing dictionary TheSaint <nobody@nowhere.net.no> - 2011-06-19 22:32 +0800
  Re: How to iterate on a changing dictionary Chris Angelico <rosuav@gmail.com> - 2011-06-20 01:13 +1000
    Re: How to iterate on a changing dictionary Roy Smith <roy@panix.com> - 2011-06-19 11:53 -0400
      Re: How to iterate on a changing dictionary Terry Reedy <tjreedy@udel.edu> - 2011-06-19 12:51 -0400
  Re: How to iterate on a changing dictionary Terry Reedy <tjreedy@udel.edu> - 2011-06-19 12:02 -0400
  Re: How to iterate on a changing dictionary Lie Ryan <lie.1296@gmail.com> - 2011-06-20 03:00 +1000
    Re: How to iterate on a changing dictionary TheSaint <nobody@nowhere.net.no> - 2011-06-20 21:20 +0800
      Re: How to iterate on a changing dictionary Florencio Cano <florencio.cano@gmail.com> - 2011-06-20 16:30 +0200
      Re: How to iterate on a changing dictionary Terry Reedy <tjreedy@udel.edu> - 2011-06-20 13:37 -0400
        Re: How to iterate on a changing dictionary TheSaint <nobody@nowhere.net.no> - 2011-06-21 18:44 +0800

csiph-web