English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python Basic Tutorial

Python Flow Control

Python Functions

Python Data Types

Python File Operations

Python Objects and Classes

Python Date and Time

Advanced Python Knowledge

Python Reference Manual

Python Dictionaries (Dictionary)

In this article, you will learn everything about Python dictionary; how to create, access, add, and delete elements, as well as various built-in methods.

What is a dictionary in Python?

Python dictionaries are an unordered collection of items. Other compound data types only have values as elements, while dictionaries have a key:value pair (key:value).

Dictionaries are optimized to retrieve values when the key is known.

How to create a dictionary?

Creating a dictionary is as simple as placing items in curly braces {} separated by commas.

An item has a key and a corresponding value, represented as a pair, key: value.

although the value can be any data type and can be repeated, the key must be an immutable type (with immutable elementsstring,numberortuple)and must be unique.

# Empty dictionary
my_dict = {}
# Dictionary with integer keys
my_dict = {1: 'apple', 2: 'ball'}
# Mixed key dictionary
my_dict = {'name': 'John', 1: [2, 4, 3}]
# Using dict()
my_dict = dict({1:'apple', 2:'ball'})
# Each item is a sequence of pairs
my_dict = dict([(1,'apple'), (2,'ball')])

As you can see above, we can also use the built-in function dict() to create a dictionary.

How to access elements in the dictionary?

Although indexing is used with other container types to access values, dictionaries use keys. Keys can be used within brackets or with the get() method.

The difference in using get() is that if the key is not found, it will return None instead of KeyError.

When the program is run, the output is:

Jack
26

How to change or add elements in the dictionary?

Dictionaries are mutable. We can use the assignment operator to add new items or change the value of existing items.

If the key already exists, the value will be updated; otherwise, a new key:value pair will be added to the dictionary.

When the program is run, the output is:

{'name': 'Jack', 'age': 27}
{'name': 'Jack', 'age': 27, 'address': 'Downtown'}

How to remove or delete elements from the dictionary?

We can use the pop() method to remove a specific item from the dictionary. This method uses the provided key to remove the item and returns the value.

The method popitem() can be used to remove and return any item (key, value) from the dictionary. The clear() method can be used to delete all items at once.

We can also use the del keyword to delete a single item or the entire dictionary itself.

When the program is run, the output is:

16
{1: 1, 2: 4, 3: 9, 5: 25}
(1, 1)
{2: 4, 3: 9, 5: 25}
{2: 4, 3: 9}
{}

Python dictionary method

The following lists the methods available for the dictionary. Some of them have been used in the above examples.

Python dictionary method
MethodDescription
clear()Remove all items from the dictionary.
copy()Return a shallow copy of the dictionary.
fromkeys(seq[v])Used to create a new dictionary with elements of the sequence seq as dictionary keys, and v as the initial value for all dictionary keys.
get(key[d])

Return the value associated with the key. If the key does not exist, return d (default is None).

items()Return an iterable array of (key, value) tuples.
keys()Return all the keys in the dictionary.
pop(key[d])Remove an item with the specified key and return its value. If the key is not found, return d. If d is not provided and the key is not found, a KeyError error is raised.
popitem()}Remove and return an arbitrary item (key, value). If the dictionary is empty, raises KeyError.
setdefault(key[d])Return the value of the specified key, if the specified key's value is not in the dictionary, return the specified value, default is None.
update([other])Using fromotherof the key/Update the dictionary with value pairs, overwriting existing keys.
values()Return all values in the dictionary as a list.

Here are some examples of using these methods.

marks = {}.fromkeys(['Math','English','Science'], 0)
# Output: {'English': 0, 'Math': 0, 'Science': 0}
print(marks)
for item in marks.items():
    print(item)
# Output: ['English', 'Math', 'Science']
list(sorted(marks.keys()))

Python Dictionary Comprehension

Dictionary comprehension is an elegant and concise way to create a new dictionary from an iterator in Python.

Dictionary comprehension includes an expression pair (key: value), followed by a for statement in curly braces {}.

This is an example of making a dictionary where each item is a pair of numbers and their squares.

squares = {x: x*x for x in range(6)}
# Output: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
print(squares)

This code is equivalent to

squares = {}
for x in range(6):
   squares[x] = x*x

Dictionary comprehension can choose to include morefororif statement.

Optional if statements can filter items to form a new dictionary.

This is an example of a dictionary that only contains odd numbers.

odd_squares = {x: x*x for x in range(11) if x%2 == 1}
# Output: {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
print(odd_squares)

For more information, please visitPython dictionary comprehension.

Other Dictionary Operations

Dictionary Membership Testing

We can use the keyword to test if a key is in the dictionary with 'in'. Note that membership testing applies only to keys, not to values.

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: True
print(1 in squares)
# Output: True
print(2 not in squares)
# Membership test is performed on keys only, not on values
# Output: False
print(49 in squares)

Iterating over the dictionary

Using a for loop, we can iterate over each key in the dictionary.

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
for i in squares:
    print(squares[i])

Built-in dictionary functions

Built-in functions such as all(), any(), len(), cmp(), sort(), etc. are usually used with dictionary to perform different tasks.

Built-in dictionary functions
FunctionDescription
all()

If all keys in the dictionary are true (or the dictionary is empty), return True.

any()

If any key in the dictionary is true, return True. If the dictionary is empty, return False.

len()Return the length (number of items) of the dictionary.
cmp()Compare items of two dictionaries.
sorted()Return the newly sorted list of keys in the dictionary.

Here are some examples of using built-in functions to process dictionaries.

squares = {1: 1, 3: 9, 5: 25, 7: 49, 9: 81}
# Output: 5
print(len(squares))
# Output: [1, 3, 5, 7, 9]
print(sorted(squares))