dictionary/hash and '1' versus 1

Stephen Hansen apt.shansen at gmail.com
Thu Jan 3 19:38:58 EST 2008


> 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.  Is there a good way to ensure that
> numbers represented as strings or ints do not get mixed up as keys?
>

Well one important thing to learn while learning Python is that while the
language is dynamically typed-- it is also /strongly/ typed. Every piece
of data has an explicit type and it doesn't change unless you change it.
It relies on duck typing a lot, and doesn't care if you mix and match
(even partially) compatible types as long as the operations are there,
but one type will always be distinct and remain that type until you
explicitly convert it.

A single integer is distinctly different from a sequence of characters in
some encoding that may just happen to contain representations of a
number.... so they'll hash differently :)

One type will basically never implicitly convert into another type.

To me, this sounds like the function should have converted the type
explicitly on return. Or maybe you need to convert it explicitly on
receipt.

But if you are in a use-case where you really don't care and only
want to hash strings, you can create a dict subclass easily that
overrides __setitem__ to always str() the input. Check out the
UserDict class.

A similar method lets you make 'case-insensitive' dicts, for example.

Were such a thing to happen automagically, you could get some
weird situations, such as "assert (key in dict) == (key in dict.keys())"
failing.

Also, do 'if key in dict' instead of 'if dict.has_key(key)'. :)

--Stephen
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080103/724420c3/attachment-0001.html>


More information about the Python-list mailing list