Dictionaries in Python
Dictionaries are one of the most powerful and flexible types in Python.
Used to store key-value pairs, they allow organizing data in a clear, efficient, and fast-to-query manner.
They are omnipresent in Python programming: configurations, API results, counts, JSON structures, etc.
Dictionary syntax
As we have seen, a Python dictionary is an unordered, mutable, and indexed collection by unique keys.
Its syntax is very simple:
my_dict = {
"name": "Alice",
"age": 30,
"city": "Paris"
}
Here:
"name"
,"age"
,"city"
are keys;"Alice"
,30
,"Paris"
are the values.
Unlike lists, elements are accessed by their key, not their position.
Creating a dictionary
There are two methods to create a dictionary.
Method #1: with curly braces
The first method that allows creating a dictionary is with curly braces {}
.
user = {"id": 101, "username": "magician", "subscribed": True}
Method #2: with the dict() method
Finally, a second way to create a dictionary is with the use of the dict()
method.
user = dict(id=101, username="magician", subscribed=True)
The
dict()
constructor is convenient but only accepts valid key names as Python identifiers (no spaces or hyphens).
Accessing a value in a dictionary
Accessing a value is very simple in a dictionary with Python: just use their keys.
user = {"username": "hugo"}
print(user["username"]) # hugo
If we try to access a key that doesn't exist, an error will be triggered.
PYTHONprint(user["email"]) # ❌ KeyError
To avoid this, it is possible to use the
get()
method which allows avoiding an error if the key is missing (very useful for data coming from APIs).PYTHONprint(user.get("email")) # None print(user.get("email", "N/A")) # N/A
Here, "N/A" is displayed only if the
Adding or modifying a value
Adding or updating an element in a dictionary is done with direct assignment:
profile = {"username": "arthur"}
profile["email"] = "arthur@example.com" # Addition
profile["username"] = "arthur42" # Modification
Easy, right? 😬
If the key doesn't exist, it is created. If it exists, its value is overwritten.
Adding multiple elements at once
Want to add multiple elements at once? It is possible to use update()
.
profile.update({"age": 29, "country": "France"})
Deleting a value
To delete an element from a dictionary, we can use one of the three available methods with the Python language: del
, pop()
and pop(key, default)
.
Method #1: del
del profile["email"]
This first method raises an error if the key doesn't exist (KeyError
).
Method #2: pop()
This second method allows deleting a value without raising an error if the element doesn't exist.
username = profile.pop("username") # Deletes and returns the value
Method #3: pop(key, default)
Finally, this last method takes method two and adds a subtlety: the possibility to define a default value to avoid any crash.
profile.pop("non_existent", "nothing") # Doesn't raise an error
Deleting all elements from a dictionary in Python
To delete all elements in a dictionary, it is possible to use the clear()
method.
profile.clear()
Iterating through a dictionary
Iterating through keys
profile = {"username": "arthur"}
for key in profile.keys():
print(key) # username
It is also possible to avoid explicitly stating "
keys()
" but it is a good practice to keep to avoid any confusion problems.PYTHONfor key in profile: print(key) # Same result here
Iterating through values
profile = {"username": "arthur"}
for value in profile.values():
print(value) # arthur
Iterating through key/value pairs
profile = {"username": "arthur"}
for key, value in profile.items():
print(f"{key} : {value}") # username : arthur
items()
is essential when you need both the key and the value.
Checking for the presence of a key in a dictionary
Before accessing a value, we can test if a key exists in the dictionary using the in
operator:
profile = {"username": "hugo", "email": "hugo@example.com"}
if "email" in profile:
print("Address found")
This should be avoided to prevent a runtime error:
PYTHONif profile["email"]: # Risk KeyError if the key doesn't exist
Dictionary comprehensions
Python allows creating a dictionary in a single line thanks to a dictionary comprehension, similar to a list comprehension.
Syntax
{key: value for element in iterable}
Example #1: Creating a dictionary of squares
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Example #2: Filtering an existing dictionary
grades = {"Alice": 18, "Bob": 12, "Chloe": 8}
passed = {k: v for k, v in grades.items() if v >= 10}
Dictionary comprehension is ideal for transforming or filtering data in a concise and readable manner.
Copying a dictionary
There are two methods to copy a dictionary: copy()
and dict()
.
Method #1: copy()
This first method makes a shallow copy (i.e., of the first level) of a dictionary.
copy = profile.copy()
To make a deep copy (with the contents of all nested elements) we must use copy.deepcopy()
:
import copy
total_copy = copy.deepcopy(original)
Method #2: dict()
To create a copy of a dictionary we also have the possibility to create... a dictionary of a dictionary! 👀
copy = dict(profile)
Merging two dictionaries
Python offers several ways to merge two dictionaries.
Method #1: with update()
a = {"name": "Alice"}
b = {"age": 30}
a.update(b)
print(a) # {'name': 'Alice', 'age': 30}
This method modifies dictionary a
directly.
Method #2: with the "|" operator
Since Python 3.9+ it is also possible to perform a merge between multiple dictionaries thanks to the |
operator.
a = {"name": "Alice"}
b = {"age": 30}
merge = a | b
print(merge) # Same result
This method is different from the first method with
update()
because it returns a new dictionary without modifyinga
/b
.
Sorting a dictionary
We can sort a dictionary by its keys or by its values.
Sorting by key
d = {"b": 2, "a": 1, "c": 3}
sorted_keys = dict(sorted(d.items()))
Sorting by value
sorted_values = dict(sorted(d.items(), key=lambda x: x[1]))
Useful methods on dictionaries
Here is an overview of the most frequently used methods on dictionaries.
Method | Description |
keys() | Returns an iterable over the keys |
values() | Returns an iterable over the values |
items() | Returns an iterable over the key/value pairs |
get(k) | Returns the value or None |
pop(k) | Deletes and returns the value |
update() | Adds or replaces elements |
clear() | Empties the dictionary |
copy() | Makes a shallow copy |
Nested dictionaries
A nested dictionary is a dictionary whose some values are themselves dictionaries.
This is very common for representing complex data structures, like JSON or hierarchical configurations.
Example
user = {
"name": "Alice",
"profile": {
"city": "Paris",
"age": 30
}
}
Accessing a nested value
print(user["profile"]["city"]) # Paris
Modifying a nested value
user["profile"]["age"] = 31
It is very easy to iterate through a nested dictionary using multiple loops.
Frequently asked questions about arrays
Let's review the questions that beginners with arrays in Python ask most!
What is the difference between
dict()
and{}
?
Both create a dictionary, but:
{}
is faster and more readable;dict()
is useful with pairs or keywords.
What's the difference between
get()
and[]
?
[]
raises an error if the key is absent while get()
returns None
(or a default value).
What is the best way to learn Python today?
With our course dedicated to Python in its latest version. 💫