Python – What makes a good dictionary key?
Python dictionaries are incredibly useful. In other programming languages, they’re called collections, hash tables, or associative arrays. If you’re an Excel user, think of what you normally do using a function like VLOOKUP or HLOOKUP. If your program needs to look up information that is indexed by some unique “key value, well, this what dictionaries are good for.
Integers work well as dictionary keys, but you should use caution in using floating point numbers (i.e. decimals). From Section 6.8 in the manual: Numeric types used for keys obey the normal rules for numeric comparison: if two numbers compare equal (such as 1 and 1.0) then they can be used interchangeably to index the same dictionary entry. (Note however, that since computers store floating-point numbers as approximations it is usually unwise to use them as dictionary keys.)”
Every item in a dictionary is a key:value pair. The key is what you’ll be using to do the lookup. Here’s an interesting and important concept: Keys must be immutable. In other words, they have to be a data type that can not be changed. Strings and numbers work. When you do some kind of string manipulation in Python, it creates a new copy in memory. Tuples work because they can’t be changed. For example,
T = (3, 4)
The tuple T does not have a method that you can call like T.append(5) or T.remove(4). If it’s a list like:
L = [3, 4]
you can use functions like .append(), .remove(), .insert() or .pop(). That means that it’s mutable, or changeable. And something that is mutable is not create a hash, or a unique identifier, for a list. Try it: hash(T) returns an integer, and hash(L) returns “TypeError: list objects are unhashable”.
Since dictionaries themselves are mutable (you can add and remove key-value pairs easily), you cannot use them as keys in other dictionaries.
More advanced stuff: If you want your own objects that you create to be dictionary keys, you have to define the method __hash__( self). See the manual section: Objects, values and types > Basic Customization.
December 17, 2009 at 5:50 pm Comments (0)
