Python Dictionaries
Learn how to store, organize, access, update, and process data using Python dictionaries and key-value pairs.
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(), andupdate(). - Loop through dictionaries efficiently.
- Work with nested dictionaries and real-world data.
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".
student = {
"name": "Ali",
"age": 21,
"course": "Python"
}
print(student["name"])
print(student["course"])
Ali Python
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.
You look up a word (the key) to find its meaning (the value).
Creating Dictionaries
Dictionaries are created using curly braces
{ }.
dictionary_name = {
key: value,
key: value
}
Example:
person = {
"name": "Sara",
"age": 25,
"city": "Lahore"
}
print(person)
{'name': 'Sara', 'age': 25, 'city': 'Lahore'}
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.75000is its value.
Dictionary keys must be unique. If the same key appears more than once, the later value replaces the earlier one.
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"])
Ali 21
If the requested key does not exist,
square-bracket access raises a
KeyError.
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"))
Ali None
You can also provide a default value.
print(student.get("course", "Not Available"))
Not Available
Changing Dictionary Values
Dictionaries are mutable, meaning their contents can be changed after creation.
student = {
"name": "Ali",
"age": 21
}
student["age"] = 22
print(student)
{'name': 'Ali', 'age': 22}
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)
{'name': 'Ali', 'age': 21, 'city': 'Multan'}
If the key already exists, its value is changed. If the key does not exist, a new item is created.
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)
21
{'name': 'Ali', 'city': 'Multan'}
Using del
del student["city"]
Using clear()
student.clear()
print(student)
{}
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))
3
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)
True False True
Membership testing on a dictionary checks keys by default, not values.
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()))
['name', 'age', 'city'] ['Ali', 21, 'Multan']
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)
name : Ali age : 21 city : Multan
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}")
Use items() when you need both the
key and value inside the loop.
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"])
Ali 22
Nested dictionaries are useful for representing structured data such as customers, products, employees, and API responses.
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)
{'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)
{'name': 'Ali', 'age': 21}
{'name': 'Ali', 'age': 30}
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)
{'name': 'Ali', 'age': 22, 'city': 'Multan'}
Existing keys are updated, while missing keys are added.
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}")
Average: 85.75
Dictionaries are commonly used when working with JSON data, APIs, configuration files, databases, web applications, analytics, and machine-learning workflows.
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)
False
The in operator checks keys by default.
Mistake 4: Expecting Duplicate Keys
student = {
"name": "Ali",
"name": "Ahmed"
}
print(student)
{'name': 'Ahmed'}
The second value replaces the first one.
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.
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.
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")
Student Information ------------------- Name: Ali Age: 21 City: Multan Course: Python Marks: 82 Result: Passed
Make the program interactive by asking the user
for the student's information with
input(). Convert marks and age to
numbers before performing calculations.
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?
Lesson Summary
Python dictionaries are one of the most useful data structures for storing structured information.
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.