Anyway to clarify this code? (dictionaries)

Mike Meyer mwm at
Wed Nov 23 05:28:02 CET 2005

"bonono at" <bonono at> writes:

> Mike Meyer wrote:
>> def my_search(another, keys, x):
>>    return dict([[k, v] for k, v in another.items() if v >= x and k in keys])
>> But then you're looking through all the keys in another, and searching
>> through keys multiple times, which probably adds up to a lot more
>> wasted work than indexing another twice.
> Would you mind clarify ? Do you mean "k in keys" is a scan rather than
> a lookup ? I find it to be pretty clean and straight forward.

I assumed keys was a simple sequence of some kind, because you passed
it to fromkeys. I guess it could be set or a dictionary, in which case
"k in keys" would be a lookup.  Were you trying to force a lookup by
creating a dict with the keys from k via fromkeys? If so, using a set
would have the same effect, and be a lot clearer:

     temp = set(keys)
     return dict([[k, v] for k, v in another.items() if v >= x and k in temp])

> I think one way or another, one need to loop through one of them, then
> index search the other. It may help a bit to take the len() and loop
> through the shorter one.

First, remember the warnings about premature optimization. The
following might be worth looking into:

      use = set(another) - set(keys)
      return dict([[k, another[k]] for k in use if another[k] >= x]

Though I still think I prefer the longhand version:

       out = dict()
       for key in set(another) - set(keys):
           if another[k] >= x:
              out[k] = another[k]

The set difference is still going to loop through one and do lookups
in the other, but it'll happen in C instead of Python.

Unless your lists are *very* long, the performance differences will
probably negligible, and are liable to change as you change the
underlying platform. So I'd recommend you choose the form that's mostt
readable to you, and go with that.

Mike Meyer <mwm at>
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.

More information about the Python-list mailing list