Python Dictionary Tutorial with Examples


Dictionaries in Python are unordered collections of items. Each item is stored as a key-value pair, allowing you to associate unique keys with specific values. Dictionaries are mutable, meaning that you can change their content by adding, modifying, or removing items.

Table of Contents

  1. Define Dictionary and Key Points
  2. Create Dictionary
  3. Access Dictionary Items
  4. Change Dictionary Items
  5. Add Dictionary Items
  6. Remove Dictionary Items
  7. Loop Dictionaries
  8. Dictionary Comprehension
  9. Nested Dictionaries
  10. Dictionary Methods
  11. Conclusion

Key Points

A dictionary is an unordered collection of key-value pairs. 

Key points about dictionaries:

  • Keys: Must be unique and immutable (e.g., strings, numbers, tuples).
  • Values: Can be of any data type and can be duplicated.
  • Mutable: Items can be added, modified, or removed.
  • Unordered: Items do not have a fixed position or order.

1. Create Dictionary

Dictionaries are created by placing items inside curly braces {}, separated by commas. Each item is a key-value pair, separated by a colon :.


# Creating a dictionary
my_dict = {"name": "Ravi", "age": 25, "city": "Mumbai"}
print(my_dict)  # Output: {'name': 'Ravi', 'age': 25, 'city': 'Mumbai'}

2. Access Dictionary Items

Dictionary items can be accessed using their keys. If the key is not found, a KeyError is raised.


# Accessing dictionary items
print(my_dict["name"])  # Output: Ravi
print(my_dict["age"])   # Output: 25

# Using the get() method to avoid KeyError
print(my_dict.get("city"))  # Output: Mumbai
print(my_dict.get("country", "India"))  # Output: India (default value if key not found)

3. Change Dictionary Items

Dictionary items can be changed by assigning a new value to an existing key.


# Changing dictionary items
my_dict["age"] = 26
print(my_dict)  # Output: {'name': 'Ravi', 'age': 26, 'city': 'Mumbai'}

4. Add Dictionary Items

New items can be added to a dictionary by assigning a value to a new key.


# Adding new dictionary items
my_dict["country"] = "India"
print(my_dict)  # Output: {'name': 'Ravi', 'age': 26, 'city': 'Mumbai', 'country': 'India'}

5. Remove Dictionary Items

Items can be removed from a dictionary using methods like pop(), popitem(), del, and clear().


# Using pop() to remove a specific item
print(my_dict)  # Output: {'name': 'Ravi', 'city': 'Mumbai', 'country': 'India'}

# Using popitem() to remove the last inserted item
print(my_dict)  # Output: {'name': 'Ravi', 'city': 'Mumbai'}

# Using del to remove a specific item
del my_dict["city"]
print(my_dict)  # Output: {'name': 'Ravi'}

# Using clear() to remove all items
print(my_dict)  # Output: {}

6. Loop Dictionaries

You can loop through the items in a dictionary using a for loop.


# Creating a dictionary
student = {"name": "Anjali", "age": 21, "course": "Computer Science"}

# Looping through keys
for key in student:
    print(key, student[key])

# Output:
# name Anjali
# age 21
# course Computer Science

# Looping through items
for key, value in student.items():
    print(key, value)

# Output:
# name Anjali
# age 21
# course Computer Science

7. Dictionary Comprehension

Dictionary comprehension provides a concise way to create dictionaries.


# Using dictionary comprehension to create a dictionary of squares
squares = {x: x**2 for x in range(1, 6)}
print(squares)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

8. Nested Dictionaries

Dictionaries can contain other dictionaries as values, creating nested dictionaries.


# Creating a nested dictionary
nested_dict = {
    "student1": {"name": "Rahul", "age": 20},
    "student2": {"name": "Sneha", "age": 22}
print(nested_dict)  # Output: {'student1': {'name': 'Rahul', 'age': 20}, 'student2': {'name': 'Sneha', 'age': 22}}

# Accessing elements in a nested dictionary
print(nested_dict["student1"]["name"])  # Output: Rahul
print(nested_dict["student2"]["age"])   # Output: 22

9. Dictionary Methods

Python dictionaries have several built-in methods, including keys(), values(), items(), update(), and copy().


# Using various dictionary methods
example_dict = {"name": "Amit", "age": 30, "city": "Pune"}

# Getting keys
keys = example_dict.keys()
print(keys)  # Output: dict_keys(['name', 'age', 'city'])

# Getting values
values = example_dict.values()
print(values)  # Output: dict_values(['Amit', 30, 'Pune'])

# Getting items
items = example_dict.items()
print(items)  # Output: dict_items([('name', 'Amit'), ('age', 30), ('city', 'Pune')])

# Updating dictionary
example_dict.update({"age": 31, "country": "India"})
print(example_dict)  # Output: {'name': 'Amit', 'age': 31, 'city': 'Pune', 'country': 'India'}

# Copying dictionary
copy_dict = example_dict.copy()
print(copy_dict)  # Output: {'name': 'Amit', 'age': 31, 'city': 'Pune', 'country': 'India'}


Python dictionaries are powerful and flexible data structures that allow you to store and manipulate collections of key-value pairs. Understanding how to create, access, modify, and perform operations on dictionaries is essential for effective programming in Python. This tutorial covered various aspects of dictionaries, including creating, accessing, changing, and removing items, as well as advanced topics like looping, dictionary comprehension, nested dictionaries, and dictionary methods. By mastering these concepts, you can efficiently work with dictionaries in your Python programs.