pop method question

James Stroud jstroud at mbi.ucla.edu
Sat Mar 3 18:22:10 EST 2007


Steven D'Aprano wrote:
> I personally don't see that pop has any advantage, especially since the
> most useful example
> 
> while some_dict:
>     do_something_with(some_dict.pop()) 
> 
> doesn't work. Instead you have to write this:
> 
> for key in some_dict.keys(): 
>     # can't iterate over the dictionary directly!
>     do_something_with(some_dict.pop(key))
> 
> which is hardly any saving over:
> 
> for key in some_dict.keys(): 
>     # can't iterate over the dictionary directly!
>     do_something_with(some_dict[key])
>     del some_dict[key]
> 
> 
> 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)

Which necessitates a key is a little cleaner than your latter example.



More information about the Python-list mailing list