Tutorials Tonight
Follow Us

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.

    Table Of Contents

  1. Python Dictionary
    1. Creating a Dictionary
    2. Accessing Dictionary Elements
  2. Adding Elements to Dictionary
    1. Updating Dictionary Elements
  3. Deleting Dictionary Elements
  4. Iterating Through Dictionary
  5. Dictionary Methods
  6. Quiz
  7. Conclusion
dictionary in python

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.

Example

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.

  1. Using curly braces {} - It is the most common way to create a dictionary. We can create an empty dictionary using curly braces.
  2. 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.

Example

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.

  1. Using the get() method - It takes the key as an argument and returns the value associated with it.
  2. 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.

Example

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.

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.

Example

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.

  1. 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.

    Example

    Let'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}
  2. 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.

    Example

    Let'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}
  3. Using the del keyword - It removes the element associated with the key passed as an argument. It doesn't return any value.

    Example

    Removing 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.

Example

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.

MethodDescription
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

Take the quiz to test your knowledge of the topic you just learned.

Which of the following is a valid key in a dictionary?

Which of the following is true about the dictionary?

Which of the following is the wrong way to define a dictionary?

To remove a key-value pair from a dictionary, which of the following method is used?

Which of the following is not a method of dictionary?


Conclusion

Summarize the lesson with a few sentences.

  1. Dictionary is a collection of key-value pairs. Use curly braces to define a dictionary.
  2. Keys in a dictionary are unique. Values in a dictionary can be duplicated.
  3. Items in a dictionary are accessed using keys.
  4. Dictionary is mutable. It can be changed after it is created.
  5. Dictionary is unordered. Items in a dictionary are not stored in any particular order.
  6. Use the len() function to find the number of items in a dictionary.
  7. Use the in operator to check if a key exists in a dictionary.
  8. You can choose a dictionary as a data structure when the data is unordered and you need to store key-value pairs.