dict1 < dict2 <=> len(dict1) <= len(dict2) ?

Tim Peters tim.one at comcast.net
Fri Oct 18 20:43:27 EDT 2002


[Thorsten Kampe]
> ...
> I just wanted to make sure that this code snippet (see above) does
> what I hoped it would.

If part of what you hoped it would do is be comprehensible, no, it's too
obscure.

> And with the "#" comment I hope no one will accuse me of writing
> perlish Python ;-)
>
> #v+
> if dict0 > dict1:  # loop through the shorter dict

Obvious is better than obscure:

    if len(dict0) > len(dict1):

is what you mean, so why not just say so?  You're not saving any measurable
time by being tricky here, and, to the contrary, if the lengths happen to be
the same, it can be unboundedly slower to compare the dicts by value instead
of by length.

>     dict0, dict1 = dict1, dict0
> for item in dict0:

The body of this loop is where the time will be spent; checking the lengths
outside the loop will take insignificant time compared to that.

indulge-in-the-obvious-at-least-once-a-day<wink>-ly y'rs  - tim





More information about the Python-list mailing list