dictionary/hash and '1' versus 1

Reedick, Andrew jr9445 at ATT.COM
Thu Jan 3 23:56:00 CET 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?

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.

It's fugly to wrap every key reference in str(), ex:
foo[str(some_func(i))].  It's tedious to add a has_key before every key
lookup.  And I have no real desire to stuff every hash inside a class in
order to ensure that keys are converted to strings.

Any good solutions or accepted practices to prevent the intermixing of
number strings and integers as hash keys?  A hash wrapper class seems to
be the best bet so far.



*****

The information transmitted is intended only for the person or entity to which it is addressed and may contain confidential, proprietary, and/or privileged material. Any review, retransmission, dissemination or other use of, or taking of any action in reliance upon this information by persons or entities other than the intended recipient is prohibited. If you received this in error, please contact the sender and delete the material from all computers. GA623





More information about the Python-list mailing list