Introduction
Python comes with a variety of built-in data structures, capable of storing different types of data. A Python dictionary is one such data structure that can store data in the form of key-value pairs - conceptually similar to a map. The values in a Python dictionary can be accessed using the keys.
In this guide, we will be discussing Python dictionaries in detail. Firstly, we'll cover the basic dictionary operations (creating a dictionary, updating it, removing and adding elements, etc.) and take a look at a couple more interesting methods afterward.
How To Create a Dictionary in Python
To create a Python dictionary, we pass a sequence of items (entries) inside curly braces {}
and separate them using a comma (,
). Each entry consists of a key and a value, also known as a key-value pair.
Note: The values can belong to any data type and they can repeat, but the keys must remain unique. Additionally, you can't assign multiple values to the same key, though, you can assign a list of values (as a single value).
The following examples demonstrate how to create Python dictionaries.
Creating an empty dictionary:
example_dict = {}
Creating a dictionary with integer keys:
example_dict = {1: 'mango', 2: 'pawpaw'}
Creating a dictionary with mixed keys:
example_dict = {'fruit': 'mango', 1: [4, 6, 8]}
Alternatevly, we can create a dictionary by explicitly calling the Python's dict()
method:
example_dict = dict({1:'mango', 2:'pawpaw'})
A dictionary can also be created from a sequence as shown below:
example_dict = dict([(1,'mango'), (2,'pawpaw')])
Dictionaries can also be nested, which means that we can create a dictionary inside another dictionary. For example:
example_dict = {1: {'student1' : 'Nicholas', 'student2' : 'John', 'student3' : 'Mercy'},
2: {'course1' : 'Computer Science', 'course2' : 'Mathematics', 'course3' : 'Accounting'}}
To print the dictionary contents, we can use Python's print()
method and pass the dictionary name as the argument to the method:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
print(example_dict)
This results in:
{'Company': 'Toyota', 'model': 'Premio', 'year': 2012}
How To Access Elements of a Python Dictionary
To access dictionary items - we pass the key, using the square bracket notation:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
x = example_dict["model"]
print(x)
This nets us the value associated with the "model" key:
Premio
You can store "configuration" items or common constants into a dictionary for ease of centralized access:
example_dict = {'Name': 'Mercy', 'Age': 23, 'Course': 'Accounting'}
print("Student Name:", example_dict['Name'])
print("Course:", example_dict['Course'])
print("Age:", example_dict['Age'])
This would result in:
Student Name: Mercy
Course: Accounting
Age: 23
The dictionary object also provides the get()
method, which can be used to access dictionary elements as well. We append the method with the dictionary name using the dot operator and then pass the name of the key as the argument to the method:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
x = example_dict.get("model")
print(x)
This results in:
Premio
Now we know how to access dictionary elements! In the next section, we'll discuss how to add new elements to an already existing dictionary.
How To Add Elements to a Python Dictionary
There are numerous ways to add new elements to a dictionary. A common way is to add a new key and assign a value to it:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
example_dict["Capacity"] = "1800CC"
print(example_dict)
When a key doesn't exist, and we assign a value to it - it gets added to the dictionary:
{'Capacity': '1800CC', 'year': 2012, 'Company': 'Toyota', 'model': 'Premio'}
The new element has Capacity
as the key and 1800CC
as its corresponding value. It has been added as the first element of the dictionary. Here is another example. First, let's first create an empty dictionary:
example_dict = {}
print("An Empty Dictionary: ")
print(example_dict)
Let's verify that it's empty:
An Empty Dictionary:
The dictionary returns nothing as it has nothing stored yet. Let us add some elements to it, one at a time:
example_dict[0] = 'Apples'
example_dict[2] = 'Mangoes'
example_dict[3] = 20
print("\n3 elements have been added: ")
print(example_dict)
This results in:
3 elements have been added:
{0: 'Apples', 2: 'Mangoes', 3: 20}
To add the elements, we specified keys as well as the corresponding values:
example_dict[0] = 'Apples'
In the above example, 0
is the key while Apples
is the value. It is even possible for us to add a set of values to one key as long as that set is referencable as a single value, such as a collection:
# These three values are implicitly converted into a set
example_dict['Values'] = 1, "Pairs", 4
print("\n3 elements have been added: ")
print(example_dict)
And we have a key with a set as its value:
3 elements have been added:
{'Values': (1, 'Pairs', 4)}
Other than adding new elements to a dictionary, dictionary elements can also be updated/changed, which we'll go over in the next section.
How To Update Dictionary Elements
After adding a value to a dictionary we can then modify the existing dictionary element. You use the key of the element to change the corresponding value:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
example_dict["year"] = 2014
print(example_dict)
In this example, we've updated the value for the key year
from the old value of 2012
to a new value of 2014
:
{'year': 2014, 'model': 'Premio', 'Company': 'Toyota'}
How To Remove Dictionary Elements
The removal of an element from a dictionary can be done in several ways, which we'll discuss one by one in this section.
The del
keyword can be used to remove the element with the specified key:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
del example_dict["year"]
print(example_dict)
This results in:
{'Company': 'Toyota', 'model': 'Premio'}
We called the del
keyword followed by the dictionary name. Inside the square brackets that follow the dictionary name, we passed the key of the element we need to delete from the dictionary, which in this example was year
. The entry for year
in the dictionary was then deleted.
Another way to delete a key-value pair is to use the pop()
method and pass the key of the entry to be deleted as the argument to the method:
Free eBook: Git Essentials
Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
example_dict.pop("year")
print(example_dict)
We invoked the pop()
method by appending it with the dictionary name. Running this code will delete the entry for year
in the dictionary:
{'Company': 'Toyota', 'model': 'Premio'}
The popitem()
method removes the last item inserted into the dictionary, without needing to specify the key. Take a look at the following example:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
example_dict.popitem()
print(example_dict)
The last entry into the dictionary was year
. It has been removed after calling the popitem()
method:
{'Company': 'Toyota', 'model': 'Premio'}
But what if you want to delete the entire dictionary? It would be difficult and cumbersome to use one of these methods on every single key. Instead, you can use the del
keyword to delete the entire dictionary:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
del example_dict
print(example_dict)
But, this code will return an error. The reason is that we are trying to access a dictionary that doesn't exist since it has been deleted beforehand:
NameError: name 'example_dict' is not defined
Depending on the use case, you might need to remove all dictionary elements but not the dictionary itself. This can be achieved by calling the clear()
method on the dictionary:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
example_dict.clear()
print(example_dict)
This will give you an empty dictionary (since all the dictionary elements have been removed):
{}
Other Common Dictionary Methods in Python
Besides methods we've covered so far, Python provides us with a lot of other interesting methods helping us perform operations other than the basic ones described before. In the following subsections, we'll take a look at some other methods you can use alongside dictionaries in Python.
len() Method
With this method, you can count the number of elements in a dictionary. For example:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
print(len(example_dict))
There are three entries in the dictionary, hence the method will return 3
:
3
copy() Method
This method returns a copy of the existing dictionary. For example:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
x = example_dict.copy()
print(x)
Let's make sure the copy is properly made and assigned to the variable x
:
{'Company': 'Toyota', 'year': 2012, 'model': 'Premio'}
After printing x
in the console, you see that it contains the same elements as those stored in the example_dict
dictionary.
Note: This is useful because modifications made to the copied dictionary won't affect the original one.
items() Method
When called, this method returns an iterable object. The iterable object has key-value pairs for the dictionary, as tuples in a list. This method is primarily used when you want to iterate through a dictionary.
The method is simply called on the dictionary object name as shown below:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
for k, v in example_dict.items():
print(k, v)
This will result in:
('Company', 'Toyota')
('model', 'Premio')
('year', 2012)
The object returned by items()
can also be used to show the changes that have been implemented in the dictionary:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
x = example_dict.items()
print(x)
example_dict["model"] = "Mark X"
print(x)
This code illustrates that when you change a value in the dictionary, the items
object is also updated to reflect this change:
dict_items([('Company', 'Toyota'), ('model', 'Premio'), ('year', 2012)])
dict_items([('Company', 'Toyota'), ('model', 'Mark X'), ('year', 2012)])
fromkeys() Method
This method returns a dictionary having specified keys and values. It takes the syntax given below:
dictionary.fromkeys(keys, value)
The value for the required keys
parameter is iterable and it specifies the keys for the new dictionary. The value for the value
parameter is optional and it specifies the default value for all the keys. The default value for this is None
.
Suppose we need to create a dictionary of three keys all with the same value, say 25
:
name = ('John', 'Nicholas', 'Mercy')
age = 25
example_dict = dict.fromkeys(name, age)
print(example_dict)
Let's verify that fromkeys()
method created the dictionary we've described:
{'John': 25, 'Mercy': 25, 'Nicholas': 25}
As expected, the fromkeys()
method was able to pick the keys and combine them with the value 25
to create the dictionary we wanted.
The value for the keys
parameter is mandatory. The following example demonstrates what happens when the value for the values
parameter is not specified:
name = ('John', 'Nicholas', 'Mercy')
example_dict = dict.fromkeys(name)
print(example_dict)
In this case, None
was used as the default value:
{'John': None, 'Mercy': None, 'Nicholas': None}
setdefault() Method
This method is applicable when we need to get the value of the element with the specified key. If the key is not found, it will be inserted into the dictionary alongside the specified default value.
The method takes the following syntax:
dictionary.setdefault(keyname, value)
In this method, the keyname
parameter is required. It represents the keyname of the item you need to return a value from. The value
parameter is optional. If the dictionary already has the key, this parameter won't have any effect. If the key doesn't exist, then the value given in this method will become the value of the key. It has a default value of None
:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
x = example_dict.setdefault("color", "Gray")
print(x)
The dictionary doesn't have the key for color
. The setdefault()
method has inserted this key and the specified value, that is, Gray
, has been used as its value:
Gray
The following example demonstrates how the method behaves if the value for the key does exist:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
x = example_dict.setdefault("model", "Allion")
print(x)
The value Allion
has no effect on the dictionary since we already have a value for the key model
:
Premio
keys() Method
This method also returns an iterable object. The object returned is a list of all keys in the dictionary. And just like with the items()
method, the returned object can be used to reflect the changes made to the dictionary.
To use this method, we only call it on the name of the dictionary, as shown below:
dictionary.keys()
For example:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
x = example_dict.keys()
print(x)
This results in:
dict_keys(['model', 'Company', 'year'])
Often times this method is used to iterate through each key in your dictionary:
example_dict = {
"Company": "Toyota",
"model": "Premio",
"year": 2012
}
for k in example_dict.keys():
print(k)
This will print each key of the example_dict
in a separate line:
Company
model
year
Conclusion
This marks the end of this guide on Python dictionaries. These dictionaries store data in key-value pairs. The key acts as the identifier for the item while the value is the value of the item. The Python dictionary comes with a variety of methods that can be applied for the retrieval or manipulation of data. In this article, we saw how a Python dictionary can be created, modified, and deleted along with some of the most commonly used dictionary methods.