dictionary/hash and '1' versus 1

John Machin sjmachin at lexicon.net
Fri Jan 4 00:14:29 CET 2008

On Jan 4, 9:56 am, "Reedick, Andrew" <jr9... at ATT.COM> wrote:
> As a Perl monkey in the process of learning Python, I just stepped on
> the "'1' (string) is not the same as 1 (integer) in regards to keys for
> dictionaries/hashes" landmine.

Congratulations. You have just stepped off the "'1' (string) is the
same as 1 (integer) in regards to several purposes" landmine.

Welcome to the awk-free world :-)

>  Is there a good way to ensure that
> numbers represented as strings or ints do not get mixed up as keys?
> Example of the problem:
>         >>> h2 = { 1 : ''}
>         >>> print h2.has_key(1)
>         True
>         >>> print h2.has_key('1')
>         False
> The problem occurred because a method used to generate keys was
> returning a string instead of a number without an explicit conversion
> taking place.  And since I was using hash.get(i, default_value) to avoid
> having to pair every key lookup with a hash.has_key(), no exception was
> thrown when the key wasn't found.

has_key is a has_been ... use "key in dict" instead of

> It's fugly to wrap every key reference in str(), ex:
> foo[str(some_func(i))].

Fugliness is in the eye of the beholder.

More information about the Python-list mailing list