12.3 Dictionary Methods

Method

Description

clear()

Removes all items from the dictionary.

copy()

Returns a shallow copy of the dictionary.

get(key,[,d])

Returns the value of the key. If the key does not exist, returns d (defaults to None).

keys()

Returns a new object of the dictionary's keys.

pop(key,[,d])

Removes the item with the key and returns its value or d if key is not found. If d is not provided and the key is not found, it raises keyError.

popitem()

Removes the last inserted key-value pair.

values()

Returns a list of all the values in the dictionary.

update()

Updates the dictionary with the specified key-value pairs.

Here are a few example use cases of these methods. It is 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.

Python Dictionary Comprehension

Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterable in Python. Dictionary comprehension consists of an expression pair (key: value) followed by a for statement inside curly braces {}.
Here is an example to make a dictionary with each item being a pair of a number and its square.

A dictionary comprehension can optionally contain more for or if statements. An optional if statement can filter out items to form the new dictionary. Here are some examples to make a dictionary with only odd items.