Dictionary Operations and Methods

del

The del statement removes a key-value pair from a dictionary. For example, the following dictionary contains the names of various fruits and the number of each fruit in stock. If someone buys all of the pears, we can remove that key-value entry from the dictionary.

=

Dictionaries are mutable, as the delete operation above indicates. As we’ve seen before with lists, this means that the dictionary can be modified by referencing an association on the left-hand side of the assignment statement. In the previous example, instead of deleting the entry for pears, we could have set the inventory to 0.

len()

Similarily, a new shipment of 200 bananas arriving could be handled like this. Notice that there are now 512 bananas— the dictionary has been modified. Note also that the len function also works on dictionaries. It returns the number of key-value pairs.

Notice that there are now 512 bananas—the dictionary has been modified. Note also that the len function also works on dictionaries. It returns the number of key-value pairs.

Methods

MethodParametersDescription
.keys()noneReturns a view of the keys in the dictionary
.values()noneReturns a view of the values in the dictionary
.items()noneReturns a view of the key-value pairs in the dictionary
.get(someKey)key Returns the value associated with key; None otherwise
.get(someKey, “some string value”)key, altReturns the value associated with key; alt otherwise

Technically, keys()values(), and items() don’t return actual lists. Like the range function described previously, they return objects that produce the items one at a time, rather than producing and storing all of them in advance as a list.

Dictionaries have a number of useful built-in methods. The above table provides a summary, and more details can be found in the Python Documentation and at W3Schools.

As we saw in previous topics for strings and lists, dictionary methods use dot notation, which specifies the name of the method to the right of the dot. and the name of the object on which to apply the method immediately to the left of the dot. For example, if x is a variable whose value is a dictionary, x.keys is the method object, and x.keys() invokes the method, returning a view of the value.

Looping (iteration)

There are three ways to iterate over the contents of a dictionary. Let’s take a moment to examine them.

The first technique involves iterating over the keys of the dictionary using the keys method. The keys method returns a collection of the keys in the dictionary.

Note the first line of the for loop:

for akey in inventory.keys():

Sorting

Each time through the loop, the loop variable, akey, is assigned a different key in the dictionary. In the loop body, the value associated with the key is accessed by indexing the dictionary with akey using the expression inventory[akey]. Note that the order in which the keys are assigned in the loop is not predictable. If you want to visit the keys in alphabetic order, you must use the sorted function to produce a sorted collection of keys, like this:

for akey in sorted(inventory.keys()):

In this case, the sorted function will arrange the keys from A to Z. If you would like to access the value for a key, you can use inventory[akey] in the loop above. Note that the sorted function is not a dictionary function, but a built-in function.

It’s so common to iterate over the keys in a dictionary that you can omit the keys method call in the for loop — iterating over a dictionary implicitly iterates over its keys.

The values method returns a collection of the values in the dictionary. Here’s an example that displays a list of the values:

The items method returns a collection of tuples, each tuple containing a key and its associated value. (A tuple is a collection which is ordered and unchangeable.) Take a look at this example that iterates over the dictionary using the items method:

Take a close look at the first line of the for loop:

for k, v in inventory.items():

Each time through the loop, k receives a key from the dictionary, and v receives its associated value. That avoids the need to index the dictionary inside the loop body to access the value associated with the key.

Note

You may have noticed in the examples above that, in order to print the result of the keys()values(), and items() methods, we used lines like this:

print(list(inventory.keys())

instead of this:

print(inventory.keys())

Technically, keys()values(), and items() don’t return actual lists. Like the range function described previously, they return objects that produce the items one at a time, rather than producing and storing all of them in advance as a list. If you need to perform an operation on the result of one of these methods such as extracting the first item, you must convert the result to a list using the list conversion function. For example, if you want to get the first key, this won’t work: inventory.keys()[0]. You need to make the collection of keys into a real list before using [0] to index into it: list(inventory.keys())[0].

Common Error

You might get an error if a key doesn’t exist and you try to retrieve it:

There are two ways to deal with this problem.

The first approach is to use the in and not in operators, which can test if a key is in the dictionary:

The second approach is to use the get method. get retrieves the value associated with a key, similar to the [] operator. The important difference is that get will not cause a runtime error if the key is not present. It will instead return the value None. There is a variation of get that allows a second parameter that serves as an alternative return value in the case where the key is not present. This can be seen in the final example below. In this case, since “cherries” is not a key, get returns 0 (instead of None).