dictionary/hash and '1' versus 1

Erik Max Francis max at alcyone.com
Fri Jan 4 10:24:48 CET 2008


Reedick, Andrew 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.

This isn't a landmine; this is a _good_ thing.  Python is strongly typed.

> Is there a good way to ensure that
> numbers represented as strings or ints do not get mixed up as keys?

Convert them all to either strings or integers (whichever is more 
useful) before you add them to the dictionary, really.

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

Then wrap it in a function or a method of one of your classes.  You only 
need to write it once.

> It's tedious to add a has_key before every key
> lookup.

There's no need to do this, though you don't say why you're bothering 
to.  Either use .setdefault, or just query and get the exception, or 
just insert the new key, value pair to override the contents.

> 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.

If you want to make sure something is always done in a particular 
situation, then solution is to have a function or method that does that, 
and then just call that function or method.  That's true in any language 
-- any one that has functions, anyway.

-- 
Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/
  San Jose, CA, USA && 37 18 N 121 57 W && AIM, Y!M erikmaxfrancis
   Laws are silent in time of war.
    -- Cicero



More information about the Python-list mailing list