PyLearn Learn Python. Build Anything.
Home Course Roadmap
Home / Python Foundations / Lesson 22
Lesson 22 · Data Collections

Python Dictionaries

Learn how to store, organize, access, update, and process data using Python dictionaries and key-value pairs.

45–55 minutes Beginner Python Foundations
0%

What You Will Learn

  • Understand what dictionaries are and when to use them.
  • Create dictionaries using key-value pairs.
  • Access, modify, add, and remove dictionary data.
  • Use important dictionary methods such as get(), keys(), values(), items(), and update().
  • Loop through dictionaries efficiently.
  • Work with nested dictionaries and real-world data.
01

What Are Dictionaries?

A dictionary is a Python data structure used to store information as key-value pairs.

Unlike a list, where we normally access data using a numerical index, dictionaries allow us to access data using meaningful keys.

For example, instead of remembering that an employee's name is stored at index 0, we can simply access it using the key "name".

Example
student = {
    "name": "Ali",
    "age": 21,
    "course": "Python"
}

print(student["name"])
print(student["course"])
Output
Ali
Python
02

Why Dictionaries Matter

Dictionaries are extremely important because real-world information is often naturally represented using labels and values.

Consider a customer:

customer = {
    "name": "Ahmed",
    "email": "ahmed@example.com",
    "city": "Multan",
    "age": 28
}

Each piece of information has a meaningful name. This makes the data easier to understand and work with.

Think of a dictionary like a real dictionary.

You look up a word (the key) to find its meaning (the value).

03

Creating Dictionaries

Dictionaries are created using curly braces { }.

Syntax
dictionary_name = {
    key: value,
    key: value
}

Example:

person = {
    "name": "Sara",
    "age": 25,
    "city": "Lahore"
}

print(person)
Output
{'name': 'Sara', 'age': 25, 'city': 'Lahore'}
04

Key-Value Pairs

Every dictionary entry consists of two parts:

  • Key — identifies the data.
  • Value — stores the actual data.
employee = {
    "name": "Usman",
    "salary": 75000,
    "department": "Sales"
}

Here:

  • "name" is a key.
  • "Usman" is its value.
  • "salary" is a key.
  • 75000 is its value.
Important

Dictionary keys must be unique. If the same key appears more than once, the later value replaces the earlier one.

05

Accessing Dictionary Values

You can access a value by placing its key inside square brackets.

student = {
    "name": "Ali",
    "age": 21,
    "grade": "A"
}

print(student["name"])
print(student["age"])
Output
Ali
21
Be careful with missing keys.

If the requested key does not exist, square-bracket access raises a KeyError.

06

Using get()

The get() method is a safer way to access dictionary values.

student = {
    "name": "Ali",
    "age": 21
}

print(student.get("name"))
print(student.get("course"))
Output
Ali
None

You can also provide a default value.

print(student.get("course", "Not Available"))
Output
Not Available
07

Changing Dictionary Values

Dictionaries are mutable, meaning their contents can be changed after creation.

student = {
    "name": "Ali",
    "age": 21
}

student["age"] = 22

print(student)
Output
{'name': 'Ali', 'age': 22}
08

Adding New Items

To add a new key-value pair, simply assign a value to a new key.

student = {
    "name": "Ali",
    "age": 21
}

student["city"] = "Multan"

print(student)
Output
{'name': 'Ali', 'age': 21, 'city': 'Multan'}
Same syntax, two purposes

If the key already exists, its value is changed. If the key does not exist, a new item is created.

09

Removing Items

Python provides several ways to remove dictionary items.

Using pop()

student = {
    "name": "Ali",
    "age": 21,
    "city": "Multan"
}

removed = student.pop("age")

print(removed)
print(student)
Output
21
{'name': 'Ali', 'city': 'Multan'}

Using del

del student["city"]

Using clear()

student.clear()

print(student)
Output
{}
10

Finding Dictionary Length

Use the len() function to count the number of key-value pairs.

student = {
    "name": "Ali",
    "age": 21,
    "city": "Multan"
}

print(len(student))
Output
3
11

Membership Testing

You can use in and not in to check whether a key exists.

student = {
    "name": "Ali",
    "age": 21
}

print("name" in student)
print("email" in student)
print("city" not in student)
Output
True
False
True
Important

Membership testing on a dictionary checks keys by default, not values.

12

keys() & values()

The keys() method returns the dictionary's keys.

student = {
    "name": "Ali",
    "age": 21,
    "city": "Multan"
}

print(student.keys())
print(student.values())

These methods provide dynamic view objects that reflect changes to the dictionary.

print(list(student.keys()))
print(list(student.values()))
Output
['name', 'age', 'city']
['Ali', 21, 'Multan']
13

items()

The items() method provides the dictionary's key-value pairs.

student = {
    "name": "Ali",
    "age": 21,
    "city": "Multan"
}

print(student.items())

It becomes especially useful when looping through a dictionary.

for key, value in student.items():
    print(key, ":", value)
Output
name : Ali
age : 21
city : Multan
14

Looping Through Dictionaries

Dictionaries can be processed using for loops.

Loop Through Keys

student = {
    "name": "Ali",
    "age": 21,
    "city": "Multan"
}

for key in student:
    print(key)

Loop Through Values

for value in student.values():
    print(value)

Loop Through Key-Value Pairs

for key, value in student.items():
    print(f"{key}: {value}")
Recommended approach

Use items() when you need both the key and value inside the loop.

15

Nested Dictionaries

A dictionary can contain another dictionary as a value. This is called a nested dictionary.

students = {
    "student1": {
        "name": "Ali",
        "age": 21
    },

    "student2": {
        "name": "Sara",
        "age": 22
    }
}

You can access nested data using multiple keys.

print(students["student1"]["name"])
print(students["student2"]["age"])
Output
Ali
22

Nested dictionaries are useful for representing structured data such as customers, products, employees, and API responses.

16

Copying Dictionaries

Assigning a dictionary to another variable does not create an independent copy.

original = {
    "name": "Ali",
    "age": 21
}

copy = original

copy["age"] = 30

print(original)
Output
{'name': 'Ali', 'age': 30}

Both variables refer to the same dictionary.

To create a separate shallow copy, use copy().

original = {
    "name": "Ali",
    "age": 21
}

copy = original.copy()

copy["age"] = 30

print(original)
print(copy)
Output
{'name': 'Ali', 'age': 21}
{'name': 'Ali', 'age': 30}
17

Using update()

The update() method adds new key-value pairs or changes existing values.

student = {
    "name": "Ali",
    "age": 21
}

student.update({
    "age": 22,
    "city": "Multan"
})

print(student)
Output
{'name': 'Ali', 'age': 22, 'city': 'Multan'}

Existing keys are updated, while missing keys are added.

18

Real-World Dictionary Examples

Product Information

product = {
    "name": "Laptop",
    "price": 125000,
    "brand": "Dell",
    "stock": 12
}

print(f"Product: {product['name']}")
print(f"Price: Rs. {product['price']}")
print(f"Stock: {product['stock']}")

Employee Record

employee = {
    "id": 101,
    "name": "Ahmed",
    "department": "Marketing",
    "salary": 85000
}

if employee["salary"] > 80000:
    print("High-value employee")

Student Marks

marks = {
    "Math": 85,
    "English": 78,
    "Computer": 92,
    "Physics": 88
}

average = sum(marks.values()) / len(marks)

print(f"Average: {average:.2f}")
Output
Average: 85.75
Why dictionaries are so important

Dictionaries are commonly used when working with JSON data, APIs, configuration files, databases, web applications, analytics, and machine-learning workflows.

19

Common Dictionary Mistakes

Mistake 1: Using a Missing Key

student = {"name": "Ali"}

print(student["age"])

This causes a KeyError.

Safer approach:

print(student.get("age", "Not available"))

Mistake 2: Forgetting the Colon

# Incorrect
student = {
    "name" "Ali"
}

Key-value pairs require a colon:

# Correct
student = {
    "name": "Ali"
}

Mistake 3: Confusing Keys and Values

student = {
    "name": "Ali"
}

print("Ali" in student)
Output
False

The in operator checks keys by default.

Mistake 4: Expecting Duplicate Keys

student = {
    "name": "Ali",
    "name": "Ahmed"
}

print(student)
Output
{'name': 'Ahmed'}

The second value replaces the first one.

20

Practice Exercises

Exercise 1 — Create a Profile

Create a dictionary containing:

  • Name
  • Age
  • City
  • Profession

Print each value separately.

Exercise 2 — Update Data

Create a product dictionary and change its price.

Exercise 3 — Add Information

Create a student dictionary and add a "grade" key after creation.

Exercise 4 — Remove Data

Create an employee dictionary and remove the "age" field using pop().

Exercise 5 — Loop Through Data

Create a dictionary containing three products and their prices. Loop through it and print each product and price.

Exercise 6 — Calculate an Average

Create a dictionary containing five subjects and student marks. Calculate the average using values().

Exercise 7 — Check a Key

Ask the user for a key and check whether that key exists in your dictionary.

21

Mini Challenge — Student Record Manager

Build a small program that stores student information using a dictionary.

Your program should store:

  • Student name
  • Age
  • City
  • Course
  • Marks

Then display the student's information and calculate whether the student has passed.

Challenge Example
student = {
    "name": "Ali",
    "age": 21,
    "city": "Multan",
    "course": "Python",
    "marks": 82
}

print("Student Information")
print("-------------------")

for key, value in student.items():
    print(f"{key.title()}: {value}")

if student["marks"] >= 50:
    print("Result: Passed")
else:
    print("Result: Failed")
Possible Output
Student Information
-------------------
Name: Ali
Age: 21
City: Multan
Course: Python
Marks: 82
Result: Passed
Challenge Upgrade

Make the program interactive by asking the user for the student's information with input(). Convert marks and age to numbers before performing calculations.

22

Quick Knowledge Check

Test your understanding before moving to the next lesson.

1. Which brackets are used to create a dictionary?

2. What does a dictionary store?

3. Which method safely retrieves a value?

4. What happens when you assign a value to an existing key?

5. Which method returns key-value pairs?

6. What does "name" in student check?

7. Which method removes an item and returns its value?

8. Which method combines new key-value pairs into a dictionary?

23

Lesson Summary

Python dictionaries are one of the most useful data structures for storing structured information.

Keys Identify data.
Values Store the actual data.
Mutable Values can be changed.
get() Safely retrieve values.
update() Add or update data.
Nested Data Store structured information.
Key takeaway

When your data consists of meaningful labels and corresponding values, a dictionary is often the natural Python data structure to use.

Ready to Continue?

You have learned how Python dictionaries store and manage structured key-value data.