Next to lists, dictionaries are one of the most useful data types in Python. Python lists, as previously shown, are ordered collections that use a numerical offset. To select an item in a list, you need to know its position within the list. Python dictionaries are unordered collections of objects, matched to a key name; in other words, you can reference an item simply by knowing its associated key.
Because of their construction, dictionaries can replace many typical search algorithms and data structures found in C and related languages. For those coming from other languages, Python dictionaries are just like a hash table or associative array, where an object is mapped to a key name.
Dictionaries include the following properties:
- They are accessed by a key, not an offset. Each item in the dictionary has a corresponding key; the key is used to call the item.
- Stored objects are in a random order to provide faster lookup. When created, a dictionary stores items in a particular order that makes sense to Python, but may not make sense to the developer.
- To get a value, simply supply the key. If you need to order the items within a dictionary, there is a container called OrderedDict that was added in Python 2.7, but it has to be imported from the collections library.
- Dictionaries are variable-length, can hold objects of any type (including other dictionaries), and support deep nesting (multiple levels of items can be in a dictionary, such as a list within a dictionary within another dictionary).
- They are mutable but can't be modified like lists or strings. They are the only data type that supports mapping; that is, a key is linked to a value.
Internally, a dictionary is implemented as a hash table.