Dictionary methodsΒΆ

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

Method Parameters Description
keys none Returns a list of the keys in the dictionary
values none Returns a list of the values in the dictionary
items none Returns a list of the key-value pairs in the dictionary
get key Returns the value associated with key; None otherwise
get key,alt Returns the value associated with key; alt otherwise

As we saw earlier with 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. The empty parentheses in the case of keys indicate that this method takes no parameters. If x is a variable whose value is a dictionary, x.keys is the method object, and x.keys() invokes the method, returning a value.

The keys method returns a list of the keys, not necessarily in the same order they were added to the dictionary or any other particular order.

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 and items methods are similar to keys. They return lists of objects which can be iterated over. Note that the item objects are tuples containing the key and the associated value.

The in and not in operators can test if a key is in the dictionary:

This operator can be very useful since looking up a non-existent key in a dictionary causes a runtime error.

The get method allows us to access 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 None. There exists 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, return 0 (instead of None).


This workspace is provided for your convenience. You can use this activecode window to try out anything you like.

Check your understanding

Next Section - Aliasing and copying