pop method question
James Stroud
jstroud at mbi.ucla.edu
Sat Mar 3 19:03:04 EST 2007
Steven D'Aprano wrote:
> On Sat, 03 Mar 2007 23:22:10 +0000, James Stroud wrote:
>
>>> To my mind, having to supply a key to dict.pop makes it rather pointless.
>>>
>>>
>>
>> I've used it in something like this and found it worthwhile:
>>
>> for akey in dict1:
>> if some_condition(akey):
>> dict2[akey] = dict2.pop(akey)
>
> Surely that's a no-op? You pop the value, than add it back again.
>
> Or do you mean dict2[akey] = dict1.pop(akey)?
>
> If so, are you sure that works? When I try it, I get "RuntimeError:
> dictionary changed size during iteration". You would need to take a copy
> of the keys and iterate over that.
>
> for key in dict1.keys():
> if some_condition(key):
> dict2[key] = dict1.pop(key)
>
>
>
Yes. You are right, both in the typo and using keys().
James
More information about the Python-list
mailing list