> 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
-- http://mail.python.org/mailman/listinfo/python-list