Chapter 18. Python’s Dictionary Implementation: Being All Things to All People
Andrew Kuchling
Dictionaries are a fundamental data type in the python programming language. Like awk’s associative arrays and Perl’s hashes, dictionaries store a mapping of unique keys to values. Basic operations on a dictionary include:
Adding a new key/value pair
Retrieving the value corresponding to a particular key
Removing existing pairs
Looping over the keys, values, or key/value pairs
Here’s a brief example of using a dictionary at the Python interpreter prompt. (To try out this example, you can just run the python command on Mac OS and most Linux distributions. If Python isn’t already installed, you can download it from http://www.python.org.)
In the following interactive session, the >>> signs
represent the Python interpreter’s prompts, and d
is the name of the dictionary I’m playing
with:
>>>d = {1: 'January', 2: 'February', ... 'jan': 1, 'feb': 2, 'mar': 3}
{'jan': 1, 1: 'January', 2: 'February', 'mar': 3, 'feb': 2} >>>d['jan'], d[1]
(1, 'January') >>>d[12]
Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 12 >>>del d[2]
>>>for k, v in d.items(): print k,v
# Looping over all pairs. jan 1 1 January mar 3 >feb 2 ...
Two things to note about Python’s dictionary type are:
A single dictionary can contain keys and values of several different data types. It’s legal to store the keys
1, 3+4j
(a complex number), and"abc"
(a string) in the same dictionary. Values retain ...
Get Beautiful Code now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.