Dictionaries in Python
A dictionary (or dict) is an unordered data structure in Python (unlike a list) that takes the form of "key-value" pairs.
In simpler terms, a dictionary is like a notebook with no specific order, where each number (value) is associated with a specific name (key).
James
+357 99 056 050
Julia
+357 96 540 432
Alexander
+357 96 830 726
Each key in a Python dictionary is completely unique, but the values can be repeated.
For example, if you add a new entry with the name "Julia" (value) and a new number (key), the entry will not duplicate but instead update the existing value.
To find a specific number, you need to provide the name. This makes Python dictionaries a convenient way to search through large datasets.
The following data types can be used as keys:
Strings
Numbers (integers and floats)
Tuples
Values can be any data type, including other dictionaries and lists.
Creating a Dictionary
This guide uses Python version 3.10.12.
Using Curly Braces {}
The simplest and most straightforward way to create a dictionary is by using curly braces.
For example, this creates an empty dictionary with no keys or values:
empty_dictionary = {}
Here’s how to create a dictionary with keys and values inside:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
The names in quotes are the keys, and the numbers are their values.
The previously shown table can be represented as a dictionary like this:
team_phones = {
"James": "+357 99 056 050",
"Julia": "+357 96 540 432",
"Alexander": "+357 96 830 726"
}
In this case, the values are of string type, not numeric.
By the way, you can also use single quotes instead of double quotes:
team_phones = {
'James': '+357 99 056 050',
'Julia': '+357 96 540 432',
'Alexander': '+357 96 830 726'
}
Using the dict() Function
As with many other types of variables, a dictionary can be created using its corresponding function.
For example, this creates an empty dictionary:
just_dictionary = dict()
And this creates a dictionary with keys and values:
keys_and_values = [("Alexander", 23), ("Victoria", 43), ("Eugene", 26), ("Meredith", 52), ("Maria", 32)]
team_ages = dict(keys_and_values)
In this case, a list of so-called tuples — pairs of "key-value" — is created first.
However, there is a more concise way to create a dictionary using the function:
team_ages = dict(Alexander = 23, Victoria = 43, Eugene = 26, Meredith = 52, Maria = 32)
Here, each function argument becomes a key with a corresponding value in the new dictionary.
Using the dict.fromkeys() Function
Another way to create a dictionary is by converting a list into a dictionary. There are a few nuances to this approach:
The elements of the list become the keys of the new dictionary.
You can specify a default value for all keys at once, rather than for each key individually.
For example, this creates a dictionary where the values of the keys will be empty:
team_names = ["Alexander", "Victoria", "Eugene", "Meredith", "Maria"] # list with keys
team_ages = dict.fromkeys(team_names)
print(team_ages)
The console output will be:
{'Alexander': None, 'Victoria': None, 'Eugene': None, 'Meredith': None, 'Maria': None}
And this creates a dictionary with a specified value, which will be common for all keys:
team_names = ["Alexander", "Victoria", "Eugene", "Meredith", "Maria"]
team_ages = dict.fromkeys(team_names, 0) # setting the default value as the second argument
print(team_ages)
The console output will be:
{'Alexander': 0, 'Victoria': 0, 'Eugene': 0, 'Meredith': 0, 'Maria': 0}
Dictionary Comprehension
A more unconventional way to create a dictionary is by generating it from other data using a so-called dictionary comprehension, which is a compact for loop with rules for dictionary generation written inside.
In this case, the generator loop iterates through the data structure from which the dictionary is created.
For example, here’s how to create a dictionary from a list with a default value for all keys:
team_names = ["Alexander", "Victoria", "Eugene", "Meredith", "Maria"]
team_ages = {name: 0 for name in team_names} # dictionary generator with 0 as the default value
print(team_ages)
The console output will be identical to the previous example:
{'Alexander': 0, 'Victoria': 0, 'Eugene': 0, 'Meredith': 0, 'Maria': 0}
However, the main advantage of this method is the ability to assign individual values to each key.
For this, you need to prepare two lists and slightly modify the basic dictionary comprehension syntax:
team_names = ["Alexander", "Victoria", "Eugene", "Meredith", "Maria"]
team_numbers = [23, 43, 26, 52, 32]
team_ages = {name: age for name, age in zip(team_names, team_numbers)} # using the zip() function to iterate over two lists simultaneously
print(team_ages)
The zip() function combines the two lists into a list of tuples, which is then iterated over in the comprehension loop.
In this case, the console output will be:
{'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32}
There is also a more complex variant that generates a dictionary from a single list containing both keys and values:
team_data = ["Alexander", 23, "Victoria", 43, "Eugene", 26, "Meredith", 52, "Maria", 32] # keys and values are stored sequentially in one list
team_ages = {team_data[i]: team_data[i+1] for i in range(0, len(team_data), 2)} # loop runs through the list with a step of 2
print(team_ages)
In this example, the range() function sets the length and iteration step for the loop.
The console output will be identical to the previous ones:
{'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32}
Adding Elements
You can add an element to a dictionary by specifying a previously non-existent key in square brackets and assigning a new value to it:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
team_ages["Catherine"] = 28 # Adding a new key-value pair
print(team_ages)
The console output will be:
{'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32, 'Catherine': 28}
Modifying Elements
Modifying an element is syntactically the same as adding one, except that the element already exists in the dictionary:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
team_ages["Victoria"] = 44 # Updating the existing value
print(team_ages)
The console output will be:
{'Alexander': 23, 'Victoria': 44, 'Eugene': 26, 'Meredith': 52, 'Maria': 32}
Accessing Elements
You can access the values in a dictionary using square brackets with the key:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
print(team_ages["Eugene"])
The console output will be:
26
Or with a more visual example using the previously shown table:
team_phones = {
"James": "+357 99 056 050",
"Julia": "+357 96 540 432",
"Alexander": "+357 96 830 726"
}
print(team_phones["Julia"])
The console output will be:
+357 96 540 432
Removing Elements
You can remove an element from a dictionary using the del keyword:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
del team_ages["Victoria"] # Deleting the element with the key "Victoria"
print(team_ages)
The console output will not contain the deleted element:
{'Alexander': 23, 'Eugene': 26, 'Meredith': 52, 'Maria': 32}
Managing Elements
A dictionary in Python has a set of special methods for managing its elements — both keys and values. Many of these methods duplicate the previously shown functions for adding, modifying, and deleting elements.
The dict.update() Function
This method adds new elements to a dictionary by passing another dictionary as an argument:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
team_ages.update({
"John": 32,
"Catherine": 28
})
print(team_ages)
The output in the console will be:
{'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32, 'John': 32, 'Catherine': 28}
The same result can be achieved by pre-creating a dictionary with the elements to be added:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
team_add = {"John": 32, "Catherine": 28}
team_ages.update(team_add)
print(team_ages)
Again, the output will be the same:
{'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32, 'John': 32, 'Catherine': 28}
The dict.get() Function
You can access the value of a dictionary not only with square brackets but also through the corresponding function:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
print(team_ages.get("Victoria"))
print(team_ages["Victoria"])
Both console outputs will be:
4343
Now, what happens if a non-existing key is passed as an argument:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
print(team_ages.get("Anastasia"))
The console output will be:
None
However, the main feature of get() compared to square brackets is the ability to specify a value for a non-existing key as the second argument:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
print(team_ages.get("Anastasia", "Non-existent employee"))
In this case, the console output will be:
Non-existent employee
When using square brackets, you would need to use a try/except block to handle cases where you are not sure if the key exists.
The dict.pop() Function
In dictionaries, there is a specific function to delete an element by key:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
team_ages.pop("Alexander")
print(team_ages)
The console output will be:
{'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32}
The dict.popitem() Function
Instead of deleting a specific element by key, you can delete the last added item:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
team_add = {"John": 32, "Catherine": 28}
team_ages.update({"John": 32})
print(team_ages)
team_ages.popitem()
print(team_ages)
The console output will show the dictionary with the added element and then its contents after the element is removed:
{'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32, 'John': 32}
{'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32}
The dict.clear() Function
You can completely clear a dictionary using the corresponding method:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
team_ages.clear()
print(team_ages)
The console output will show an empty dictionary:
{}
The dict.copy() Function
You can fully copy a dictionary:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
team_ages_copy = team_ages.copy()
print(team_ages)
print(team_ages_copy)
The console output will contain the same content from two different dictionaries:
{'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32}
{'Alexander': 23, 'Victoria': 43, 'Eugene': 26, 'Meredith': 52, 'Maria': 32}
The dict.setdefault() Function
Sometimes, the mechanics of adding or retrieving a key are not enough. Often, you need more complex behavior. For example, in some cases, you need to check for the presence of a key and immediately get its value, and if the key doesn't exist, it should be automatically added.
Python provides a special method for this operation:
team_ages = {"Alexander": 23, "Victoria": 43, "Eugene": 26, "Meredith": 52, "Maria": 32}
print(team_ages.setdefault("Alexander")) # This key already exists
print(team_ages.setdefault("John")) # This key doesn't exist, so it will be created with the value None
print(team_ages.setdefault("Catherine", 29)) # This key doesn't exist, so it will be created with the value 29
The console output will show results for all requested names, regardless of whether they existed at the time of the function call:
23None29
Dictionary Transformation
You can extract data from a dictionary's keys and values. Typically, this extraction operation is performed to convert the dictionary into another data type, such as a list.
There are several functions for extracting data from a dictionary in Python:
dict.keys() — returns an object with the dictionary's keys
dict.values() — returns an object with the dictionary's values
dict.items() — returns an object with "key-value" tuples
Here's an example of how to extract data from a dictionary and convert it into a list:
team_phones = {
"James": "+357 99 056 050",
"Julia": "+357 96 540 432",
"Alexander": "+357 96 830 726"
}
# All returned objects are converted into lists using the list() function
team_names = list(team_phones.keys()) # List of dictionary keys
team_numbers = list(team_phones.values()) # List of dictionary values
team_all = list(team_phones.items()) # List of "key-value" pairs
print(team_names)
print(team_numbers)
print(team_all)
The console output will be:
['James', 'Julia', 'Alexander']
['+357 99 056 050', '+357 96 540 432', '+357 96 830 726']
[('James', '+357 99 056 050'), ('Julia', '+357 96 540 432'), ('Alexander', '+357 96 830 726')]
In the above example, the returned objects from the dictionary are explicitly converted into lists.
However, this step is not necessary:
team_phones = {
"James": "+357 99 056 050",
"Julia": "+357 96 540 432",
"Alexander": "+357 96 830 726"
}
print(team_phones.keys())
print(team_phones.values())
print(team_phones.items())
The console output will be:
dict_keys(['James', 'Julia', 'Alexander'])
dict_values(['+357 99 056 050', '+357 96 540 432', '+357 96 830 726'])
dict_items([('James', '+357 99 056 050'), ('Julia', '+357 96 540 432'), ('Alexander', '+357 96 830 726')])
Conclusion
In Python, a dictionary is an unordered data structure in the form of "key-value" pairs, with which you can perform the following operations:
Creating a dictionary from scratch
Generating a dictionary from other data
Adding elements
Modifying elements
Accessing elements
Removing elements
Managing elements
Transforming the dictionary
Thus, a dictionary solves many problems related to finding a specific value within a large data structure — any value from the dictionary is retrieved using its corresponding key.
If you want to build a web service using Python, you can rent a cloud server at competitive prices with Hostman.
10 January 2025 · 12 min to read