๐ฏ Lesson Objective
To understand how to create, access, and manipulate dictionaries โ one of Pythonโs most powerful data structures for storing key-value pairs.
๐งฉ 1. What Is a Dictionary?
A dictionary is a collection of key-value pairs enclosed in curly braces {}.
Each key is unique, and it is used to access its corresponding value.
โ Example:
student = {
"name": "Sameer",
"age": 25,
"city": "Warangal"
}
print(student)
Output:
{'name': 'Sameer', 'age': 25, 'city': 'Warangal'}
โ๏ธ 2. Accessing Dictionary Elements
You can access values using their keys.
print(student["name"]) # Using key directly
print(student.get("age")) # Using get() method
Output:
Sameer
25
๐งฑ 3. Adding and Updating Items
โ Add a New Key-Value Pair
student["course"] = "Python"
print(student)
โ Update Existing Value
student["age"] = 26
print(student)
Output:
{'name': 'Sameer', 'age': 26, 'city': 'Warangal', 'course': 'Python'}
โ 4. Removing Items
| Method | Description | Example |
|---|---|---|
pop(key) | Removes key and returns value | student.pop("city") |
del | Deletes key-value pair | del student["age"] |
clear() | Removes all items | student.clear() |
โ Example:
student.pop("city")
print(student)
Output:
{'name': 'Sameer', 'age': 25}
๐ 5. Looping Through a Dictionary
โ Loop Through Keys:
for key in student:
print(key)
โ Loop Through Values:
for value in student.values():
print(value)
โ Loop Through Both:
for key, value in student.items():
print(key, ":", value)
Output:
name : Sameer
age : 25
city : Warangal
๐งฎ 6. Checking for Keys
You can verify if a key exists using the in operator.
if "name" in student:
print("Name exists!")
Output:
Name exists!
๐ฆ 7. Dictionary Methods
| Method | Description | Example |
|---|---|---|
keys() | Returns all keys | student.keys() |
values() | Returns all values | student.values() |
items() | Returns key-value pairs | student.items() |
copy() | Returns a shallow copy | student.copy() |
update() | Adds or updates multiple items | student.update({"country": "India"}) |
โ Example:
student.update({"country": "India", "language": "English"})
print(student)
Output:
{'name': 'Sameer', 'age': 25, 'city': 'Warangal', 'country': 'India', 'language': 'English'}
๐ 8. Nested Dictionaries
You can store dictionaries inside other dictionaries.
โ Example:
students = {
"s1": {"name": "Ali", "age": 22},
"s2": {"name": "Sara", "age": 21},
"s3": {"name": "John", "age": 23}
}
print(students["s2"]["name"])
Output:
Sara
๐ 9. Dictionary Comprehension
Create a dictionary in one line using comprehension.
โ Example:
squares = {x: x*x for x in range(5)}
print(squares)
Output:
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
๐ 10. Real-Life Example โ Contact Book
contacts = {
"Ali": "9876543210",
"Sara": "9123456789",
"John": "9988776655"
}
name = input("Enter name: ")
if name in contacts:
print(f"{name}'s number is {contacts[name]}")
else:
print("Contact not found.")
Output:
Enter name: Sara
Sara's number is 9123456789

Leave a Reply