Dictionary in Python
In this tutorial, we will learn about the dictionary data type in Python. We will also learn how to create a dictionary, access its elements, and perform various operations on it.
- Python Dictionary
- Adding Elements to Dictionary
- Deleting Dictionary Elements
- Iterating Through Dictionary
- Dictionary Methods
- Quiz
- Conclusion
Table Of Contents
Python Dictionary
A dictionary is a collection of key-value pairs. It is an unordered and mutable data type (that can be changed). It is represented by curly braces {}
.
It is similar to a list, but instead of using indexes to access elements, we use keys. The keys are unique and immutable. The values can be of any data type and can be duplicated.
Let's see an example of a dictionary.
Let's create a dictionary of fruits and their prices.
fruits = {
"apple": 10,
"banana": 20,
"orange": 30,
"grapes": 10
}
print(fruits)
{'apple': 10, 'banana': 20, 'orange': 30, 'grapes': 10}
Here, the keys are the names of the fruits and the values are their prices. We can access the values by using the keys.
Creating a Dictionary
We can create a dictionary in 2 different ways.
- Using curly braces {} - It is the most common way to create a dictionary. We can create an empty dictionary using curly braces.
- Using the dict() function - It takes a list of tuples as an argument and returns a dictionary.
Let's see an example of both methods.
Let's create a dictionary of fruits and their prices.
# 1. Using curly braces
fruits = {
"apple": 10,
"banana": 20,
"orange": 30
}
print(fruits)
# 2. Using dict() function
fruits = dict([
("apple", 10),
("banana", 20),
("orange", 30)
])
print(fruits)
{'apple': 10, 'banana': 20, 'orange': 30} {'apple': 10, 'banana': 20, 'orange': 30}
Note: In python dictionary key can be any immutable type including tuple, string, number, boolean, etc. But not list, set, dictionary, etc as they are mutable. But it is recommended to use string as a key in dictionary.
Accessing Dictionary Elements
We can use 2 different ways to access the elements of a dictionary.
- Using the get() method - It takes the key as an argument and returns the value associated with it.
- Using the square brackets - It is similar to accessing elements of a list. We use the key inside the square brackets to access the value.
Let's see an example of both methods.
Let's access the price of fruits.
fruits = {
"apple": 10,
"banana": 20,
"orange": 30,
"grapes": 10
}
# 1. Using get() method
print("Price of apple is", fruits.get("apple"))
# 2. Using square brackets
print("Price of banana is", fruits["banana"])
Price of apple is 10 Price of banana is 20
Adding Elements to a Dictionary
Dictionary is a mutable data type. We can add new elements to it.
To add a new element, use the square brackets, pass a new key and assign a value to it.
Let's see an example.
Let's add a new fruit to the dictionary.
fruits = {
"apple": 10,
"banana": 20
}
print("Before adding new fruit:", fruits)
# Add a new fruit
fruits["orange"] = 30
print("After adding new fruit:", fruits)
Before adding new fruit: {'apple': 10, 'banana': 20} After adding new fruit: {'apple': 10, 'banana': 20, 'orange': 30}
Note: If the key already exists, the value will be updated.
Updating Items in a Dictionary
We have in 2 different ways to update items in a dictionary. First using the above method and second using the update() method.
The update() method takes a dictionary as an argument and updates the dictionary with the new values.
Let's see an example of this.
Let's update the price of apple.
fruits = {
"apple": 10,
"banana": 20,
"orange": 30
}
print("Before updating:", fruits)
# Update the price of apple
fruits["apple"] = 15
print("After updating:", fruits)
Before updating: {'apple': 10, 'banana': 20, 'orange': 30} After updating: {'apple': 15, 'banana': 20, 'orange': 30}
Note: If the key doesn't exist, a new element will be added to the dictionary.
Removing items from a Dictionary
Here are 3 different ways to remove items from a dictionary.
-
Using the pop() method - It takes the key as an argument and removes the element associated with it. It returns the value of the removed element.
ExampleLet's remove the apple from the dictionary.
fruits = { "apple": 10, "banana": 20, "orange": 30 } print("Before removing:", fruits) # Removing apple fruits.pop("apple") print("After removing apple:", fruits) # Removing banana fruits.pop("banana") print("After removing banana:", fruits)
Before removing: {'apple': 10, 'banana': 20, 'orange': 30} After removing apple: {'banana': 20, 'orange': 30} After removing banana: {'orange': 30}
-
Using the popitem() method - It removes the last inserted element from the dictionary. It returns the key and value of the removed element as a tuple.
ExampleLet's remove the last inserted element from the dictionary.
fruits = { "apple": 10, "banana": 20, "orange": 30 } print("Before removing:", fruits) # Removing the last inserted element fruits.popitem() print("After removing:", fruits)
Before removing: {'apple': 10, 'banana': 20, 'orange': 30} After removing: {'apple': 10, 'banana': 20}
-
Using the del keyword - It removes the element associated with the key passed as an argument. It doesn't return any value.
ExampleRemoving apple from the dictionary.
fruits = { "apple": 10, "banana": 20, "orange": 30 } # Removing apple del fruits["apple"] print(fruits)
{'banana': 20, 'orange': 30}
Iterating Through a Dictionary
There are multiple different ways to access the elements in a dictionary.
for loop in Python is the most common way to iterate through a dictionary.
Let's see 3 different ways to iterate through a dictionary.
Let's iterate through the dictionary.
fruits = {
"apple": 10,
"banana": 20
}
# Iterating through the dictionary
print("Method 1: using items() method")
for key, value in fruits.items():
print(key, value)
print("Method 2: using keys() method")
for key in fruits.keys():
print(key, fruits[key])
print("Method 3: access keys directly")
for key in fruits:
print(key, fruits[key])
Method 1: using items() method ('apple', 10) ('banana', 20) Method 2: using keys() method ('apple', 10) ('banana', 20) Method 3: access keys and values directly ('apple', 10) ('banana', 20)
Dictionary Methods
There are many built-in methods available for dictionaries. Each method has a different purpose.
Let's see some of the most commonly used methods with their usage.
Method | Description |
---|---|
clear() | Removes all the elements from the dictionary. |
copy() | Returns a shallow copy of the dictionary. |
fromkeys() | Returns a dictionary with the specified keys and values. |
get() | Returns the value of the specified key. |
items() | Returns a list containing a tuple for each key-value pair. |
keys() | Returns a list containing the dictionary's keys. |
pop() | Removes the element with the specified key. |
popitem() | Removes the last inserted key-value pair. |
setdefault() | Returns the value of the specified key. If the key does not exist: insert the key, with the specified value. |
update() | Updates the dictionary with the specified key-value pairs. |
values() | Returns a list of all the values in the dictionary. |
Quiz - Python dictionary tutorial quiz
Conclusion
Summarize the lesson with a few sentences.
- Dictionary is a collection of key-value pairs. Use curly braces to define a dictionary.
- Keys in a dictionary are unique. Values in a dictionary can be duplicated.
- Items in a dictionary are accessed using keys.
- Dictionary is mutable. It can be changed after it is created.
- Dictionary is unordered. Items in a dictionary are not stored in any particular order.
- Use the
len()
function to find the number of items in a dictionary. - Use the
in
operator to check if a key exists in a dictionary. - You can choose a dictionary as a data structure when the data is unordered and you need to store key-value pairs.