More random python observations from a perl programmer

Tom Christiansen tchrist at
Thu Aug 19 12:59:20 EDT 1999

     [courtesy cc of this posting mailed to cited author]

In comp.lang.python, 
    jblaine at (Jeff Blaine) writes:
:>GOTCHA: (low)
:>    You can't use "in" on dicts.  Instead, you must use 
:>	d = { "fred":"wilma", "barney":"betty" }
:>	if d.has_key("fred"):	# legal
:>	if "fred" in d:	        # ILLEGAL
:>    I don't understand why this was done.
:I'm very curious what would you think should be legal.
:Would 'in' (when used on a dict) search the keys, values, or both?
:Each one of those seem like a bad idea to me.  You have 2 separate
:areas containing data.  Searching each of those individually 
:(has_key()...) seems right to me.

Well, it's the polymorphism thing.  If "+" is supposed to work on anything
(which I don't agree with, but that's not my decision), I don't understand
why "in" shouldn't.  I keep thinking that everything should work on
everything.  For example, this surprises me:

    x = {1:2, 3:4}
    y = {10:20, 30:40}
    z = x + y

The latter isn't legal.  But in Perl, you can merge hashes easily.

    %x = (1,2,3,4);
    %y = (10,20,30,40);
    %z = (%x, %y);

    print $z{1}
    print $z{30}

If you want to do it all with references, and use pretty => arrows,
it would look like this:

    $x = {1 =>2, 3 =>4};
    $y = {10 =>20, 30 =>40);
    $z = { %$x, %$y };

    print $z->{1}
    print $z->{30}

Of course, that's not super efficient.  And that overright duplicates,
rather than making lists of them.  Still, that's not a bad behaviour.

I can't get used to not being able to do hash slices, as in

    @revhash{values %hash} = keys %hash;


    print sort(@hash{@desired})

But I surely see your point about not knowing whether it's a key or
a value.  The only sane thing would be the key, but that's what has_key
does.  I say "sane" because otherwise you'd need to search all the values,
and as Larry Wall says, "Doing linear scans over an associative array is
like trying to club someone to death with a loaded Uzi." (Perl Cookbook,
Chapter 5, intro). :-)

I've always resisted adding "in" to Perl because I really want people
to get out of the habit of doing linear scans, because hashing it up
into a lookup mapping is almost always the right thing in the long
run, just not for one-offs.

:Thanks for the document.  It was very interesting reading.

You're welcome.  I got so fed up with the damned flames coming
from people who don't actually even know what they're talking about,
that I decided to make sure I wasn't one of them. :-)

Can you sum up plan 9 in layman's terms? It does everything 
    Unix does only less reliably    --Ken Thompson

More information about the Python-list mailing list