Dictionary is the term that
Python uses for the
data structure known
elsewhere as an
associative array or
hash.
A dictionary is similar to an array, and the syntax for using dictionaries is similar to that for arrays. There are two basic differences between an array and a dictionary:
- The keys of an array are whole numbers, whereas the keys of a dictionary may be of any immutable type -- most commonly strings, but floats, complex numbers, tuples, or even types are possible.
- The entries of a dictionary are not ordered. That is to say, there is no first (or zeroth) entry, and there is no succession from a given entry to a next entry. To iterate over the entries, one must use a method such as keys() to create an array from the dictionary, or (in Python 2.1) use an iterator.
To write a dictionary literal, use curly braces:
color = {"banana": "yellow", "cherry": "red", "orange": "orange"}
To look a key up in a dictionary, use square brackets:
print color["banana"]
Python dictionaries differ from Perl hashes in one major respect: whereas the keys of a Perl hash must be of scalar type, a Python dictionary's keys may be of any immutable type. Therefore, tuples and the like can be used as hash keys.