Dictionaries

NoteWhat is a dictionary?

Along with lists, dictionaries are one of the most flexible built-in data types in Python. If you think of lists as ordered collections of objects, you can think of dictionaries as unordered collections; the chief distinction is that in dictionaries, items are stored and fetched by key instead of by positional offset.

NoteWhy should I use a dictionary?

Dictionaries take the place of records, search tables, and any other sort of aggregation where item names are more meaningful than item positions.

NoteWhat type of objects can I include in a dictionary?

Like lists, dictionaries can contain objects of any type, and they support nesting to any depth (they can contain lists, other dictionaries, and so on). Each key can have just one associated value, but that value can be a collection of multiple objects if needed, and a given value can be stored under any number of keys.

NoteHow do I create a dictionary?

Snippet 4.15 shows two different ways to create a dictionary. A dictionary can be created by including key-value pairs among curly braces (see line 2). In the example, there are three keys associated with Marvel characters and as many values, which can be thought of as the characters’ position in an ideal power rank. A colon separates a key and its associated value. The second way to create a dictionary is based on Python’s builtin dict, mapping key onto values, and zip, which iterates over two elements in parallel. Specifically, zip creates the one-to-one correspondence between keys (characters) and values (character’s power) that is passed as the argument of dict. We will analyze the topic of iterations extensively in later sections.

# method 1
>>> D = {"Captain Marvel": 3, "Living Tribunal": 2, "One-Above-All": 1}

# method 2
>>> CHARACTERS = ["Captain Marvel", "Living Tribunal", "One-Above-All"]
>>> RANK = [3, 2, 1]
>>> D = dict(zip(CHARACTERS, RANK))
>>> print(D)
{"Captain Marvel": 3, "Living Tribunal": 2, "One-Above-All": 1}
NoteHow do I fetch a dictionary’s values?

Dictionaries’ items cannot be accessed via positional offsets — like lists. Instead, we fetch the individual items using the dictionary keys shown in Snippet 4.16 (see line 5). The reference key is passed among brackets. When the dictionary at hand contains nested dictionaries (see line 9), it is possible to concatenate multiple queries, namely, sequences of keys between brackets (see line 21).

# the dictionary
>>> D = {"Captain Marvel": 3, "Living Tribunal": 2, "One-Above-All": 1}

# let's fetch Captain Marvel's position in the Marvel characters' power rank
>>> D["Captain Marvel"]
3

# a dictionary of dictionaries
>>> D = {
    "Dr. Strange": {
        "first_appearance": 1963,
        "created_by": "Lee & Ditko"
        },
    "Iron Man": {
        "first_appearance": 1963,
        "created_by": "Lee, Lieber, Heck & Kirby"
        },
    }

# let us fetch the creator of Dr. Strange
>>> D["Dr. Strange"]["created_by"]
"Lee & Ditko"
NoteAre dictionaries mutable?

Dictionaries, like lists, are mutable. Thus, we can change, expand, and shrink them in place without making new dictionaries: simply assign a value to a key to change or create an entry. The del statement works here, too; it deletes the entry associated with the key specified as an index (see Snippet 4.17).

# the dictionary
>>> D = {"Captain Marvel": 3, "Living Tribunal": 2, "One-Above-All": 1}

# let us change the power rank for Captain Marvel
>>> D["Captain Marvel"] = 12
>>> print(D)
{"Captain Marvel": 12, "Living Tribunal": 2, "One-Above-All": 1}

# let us eliminate the character Living Tribunal
>>> del D["Living Tribunal"]
>>> print(D)
{"Captain Marvel": 12, "One-Above-All": 1}

# let us add a further character
>>> D["Wanda Maximoff"] = 4
>>> print(D)
{"Captain Marvel": 12, "One-Above-All": 1, "Wanda Maximoff": 4}
NoteWhat are the most common methods to manipulate a dictionary?

Like for lists, Python offers many methods to manipulate dictionary objects. Table 4.7 reports some of the most common methods and synopses. The first three methods, .keys() .values() .items(), get the constitutive elements of dictionaries: keys, values, and key-value pairs, respectively. The fourth method, .get(key, default?) gets the value for a specific key. The fifth method, .update(), updates the value for a specific key. Like .update(), .popitem(), .pop(), and d.clear() alter the information of a dictionary in place. The first removes the value of a certain key; the second removes the item (a key-value pair) for a certain key; the latter deletes all dictionary items. Finally, .copy() creates a shallow copy of an existing dictionary.

Table 1: Popular Dictionary Methods
Method Synopsis
D.keys() Get all dictionary keys
D.values() Get all dictionary values
D.items() Get all dictionary key-value pairs as tuples
D.get(key, default?) Query a dictionary element by key
D.update(D2) Update a dictionary key’s value
D.popitem() Remove the value corresponding to a certain key
D.pop(key, default?) Remove the item at the given position in the list
D.clear() Delete all dictionary items
D.copy() Copy the target dictionary
NoteHow do I access the information in a dictionary?

Snippet 4.18 shows how to use built-in methods to carry out three fundamental tasks: accessing dictionary keys (see line 5), values (see line 9), and items (i.e., key-value pairs, see line 13). It is worth noticing that the three methods illustrated in the example yield specific dictionary objects such as dict_keys, dict_values, and dict_items. Translating one of these dictionary objects into a list — if needed — is straightforward (see line 17).

# the dictionary
>>> D = {"Captain Marvel": 3, "Living Tribunal": 2, "One-Above-All": 1}

# get the keys
>>> D.keys()
dict_keys(["Captain Marvel", "Living Tribunal", "One-Above-All"])

# get the values
>>> D.values()
dict_values([3, 2, 1])

# get the items
>>> D.items()
dict_items([("Captain Marvel", 3), ("Living Tribunal", 2), ("One-Above-All", 1)])

# get the keys as a list
>>> list(D.keys())
["Captain Marvel", "Living Tribunal", "One-Above-All"]