5.5. Dictionaries
Another useful data type built into Python is the dictionary (see Mapping Types — dict). Dictionaries are sometimes found in other languages as “associative memories” or “associative arrays”. Unlike sequences, which are indexed by a range of numbers,dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys.Tuples can be used as keys if they contain only strings, numbers, or tuples;if a tuple contains any mutable objecteither directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().
It is best to think of a dictionary as an unordered set of key: value pairs,with the requirement that thekeys are unique(within one dictionary). A pair of braces creates an empty dictionary: {}. Placing a comma-separated list of key:value pairs within the braces adds initial key:value pairs to the dictionary; this is also the way dictionaries are written on output.
The main operations on a dictionary are storing a value with some key and extracting the value given the key. It is also possible to delete a key:value pair with del. If you store using a key that is already in use, the old value associated with that key is forgotten. It is an error to extract a value using a non-existent key.
Performing list(d.keys()) on a dictionary returns a list of all the keys used in the dictionary, in arbitrary order (if you want it sorted, just use sorted(d.keys()) instead). [2] To check whether a single key is in the dictionary, use the inkeyword.
Here is a small example using a dictionary:
The dict() constructor builds dictionaries directly from sequences of key-value pairs:
In addition, dict comprehensions can be used to create dictionaries from arbitrary key and value expressions:
When the keys are simple strings, it is sometimes easier to specify pairs using keyword arguments:
5.6. Looping Techniques
When looping through dictionaries, the key and corresponding value can be retrieved at the same time using theitems() method.
When looping through a sequence, the positionindex andcorresponding value can be retrieved at the same time using the enumerate() function.
To loop over two or moresequences at the same time, the entries can bepaired with the zip() function.
To loop over asequence in reverse, first specify the sequence in a forward direction and then call the reversed()function.
To loop over asequence insorted order, use the sorted() function which returns a new sorted list while leaving the source unaltered.
To change a sequence you are iterating over while inside the loop(for example toduplicate certain items), it is recommended that you firstmake a copy. Looping over a sequence does not implicitly make a copy.The slice notation makes this especially convenient: