Optimisation Hints (dict processing and strings)

John Machin sjmachin at lexicon.net
Tue Mar 29 23:22:43 CEST 2005

OPQ wrote:
> (2)- in a dict mapping a key to a list of int, remove every entrie
> where the list of int have of length < 2
> So far, my attempts are
> for (2):
> for k in hash.keys()[:]: # Note : Their may be a lot of keys here
>    if len(hash[k])<2:
>       del hash[k]
> Here again, I think the hash.keys duplication can be time *and*
> consuming. But still better than (I suppose - no time it yet)
> hash=dict([(k,v) for (k,v) in hash if len(v)>1])

Firstly, don't call it "hash"; you are shadowing a built-in function --
as well as giving clues to your background :-)

Secondly, you are *triplicating* the keys. Mapping.keys() returns a
list. You can safely iterate over that to change the contents of the
mapping. Read the docs: "a.keys() a copy of a's list of keys".
Mapping.keys()[:] gives you a copy of the copy. 


More information about the Python-list mailing list