Python dictionaries do not have to have restrictions on how data structures are implemented in other languages.
The constraints for an object to be used as a dictionary key are: the object must implement a method __hash__
that returns a unique and constant value; the object has equality comparison with other objects (__eq__
) - and that neither this hash nor the equality condition varies as long as the object is a dictionary key. In general, to simplify we say that immutable objects can be dictionary keys - but by following these constraints even mutable objects can serve.
The "what the utility" varies enormously: it depends on what you want to do - tuples in general are practical because they let you use a dictionary as a sparse matrix, face - just use the "get" method to pick up values:
W = H = 10
a = {}
a[5,5] = 1
print ("\n".join(", ".join(str(a.get((x,y), 0)) for x in range(W)) for y in range(H)) )
In this example, I use the index in the method get
why it allows specifying a default value for when the key does not exist - (which happens for all combinations of x and y, except for (5,5) that I declared). The exit is:
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 1, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
0, 0, 0, 0, 0, 0, 0, 0, 0, 0
Tuples are exceptionally practical because the surrounding parentheses can be omitted when used in an unambiguous context - as indexes within brackets (see example above).
But objects that represent date and time, with rich comparisons, frozen sets (Frozen sets), even functions can be used as dictionary keys (in log applications, for example, that count the number of times a function is called, or that cache) - it is legal not to have an artificial restriction.
A context in which different keys should be taken care of is in applications that have to serialize the data as JSON, for example, Rest Apis, or in calls to some non-relational databases: the JSON standard requires that dcionary chavves be strings.
I have this doubt because I come from PHP, and, "there", you cannot define an index of an array as another type that is not int or string (nor does float accept).
– Wallace Maxters
Beware that Python dictionaries are quite different from "arrays" in PHP - "arrays" in PHP are a type of wildcard object, which works both as a sequence, with numerical inidces and as a mapping with string keys. They are separate concepts, which in Pyrhon are well separated - the most common types are lists and tuples for sequences, and dictionaries for mapping.
– jsbueno