Optimisation Hints (dict processing and strings)

Bengt Richter bokr at oz.net
Wed Mar 30 03:33:57 EST 2005


On 29 Mar 2005 23:41:15 -0800, poyol at hotmail.com (OPQ) wrote:
[...]

>> > for k in hash.keys()[:]: # Note : Their may be a lot of keys here
>> >    if len(hash[k])<2:
>> >       del hash[k]
>> 
>> - Try if it isn't faster to iterate using items instead of iterating 
>> over keys
>
>items are huge lists of numbers. keys are simple small strings. And
>even if it is faster, how can I find the key back, in order to delete
>it ?
items() returns a list of (k,v) tuples, so you can unpack them
into the for assignment target, e.g.,

 for k,v in hashh.items():
     if len(v)<2:
            del hassh[k]

>for v in hashh.items():
>    if len(v)<2:
>           del ???????
>

but to avoid a big temporary items() list, perhaps (untested)

 for k in [k for k,v in hashh.iteritems() if len(v)<2]:
     del hassh[k]

UIAM that should build a temporary safe list
only of the keys selected for deletion.

Regards,
Bengt Richter



More information about the Python-list mailing list