Now let's move to another extremely important Python data structure.
📖 Phase 1: Programming Fundamentals
📌 Topic 18: Dictionaries in Python 🗂️
A dictionary is a Python data structure used to store data in key-value pairs.
In Python:
student = {
"name": "Alex",
"age": 21,
"course": "Python"
}
Here:
"name" → key
"Alex" → value
"age" → key
21 → value
🔹 1. Why Do We Need Dictionaries?
Suppose you have this list:
student = ["Alex", 21, "Python"]
You need to remember that:
Index 0 = name
Index 1 = age
Index 2 = course
That's not very readable.
With a dictionary:
student = {
"name": "Alex",
"age": 21,
"course": "Python"
}
print(student["name"])
Output:
Alex
🔹 2. Creating a Dictionary
Use curly braces
{} with key-value pairs:person = {
"name": "John",
"age": 25,
"city": "Delhi"
}
You can also create an empty dictionary:
data = {}
# Or
data = dict()
⚠️ Remember:
{} creates an empty dictionary, not an empty set. For an empty set: set()🔹 3. Dictionary Keys and Values
A dictionary contains: Key → Value
employee = {
"name": "Sam",
"salary": 50000,
"department": "IT"
}
Keys: name, salary, department
Values: Sam, 50000, IT
You can get them using:
employee.keys()
employee.values()
employee.items()
🔹 4. Accessing Dictionary Values
Using a key:
student = {
"name": "Alex",
"age": 21
}
print(student["name"]) # Alex
You can also use
.get():print(student.get("name")) # Alex
What is the difference?
If the key doesn't exist:
student["city"] ❌ Raises KeyError.But:
student.get("city") ✅ Returns: NoneYou can also provide a default value:
student.get("city", "Unknown") # Output: Unknown
🔹 5. Adding New Items
Simply assign a value to a new key:
student = {
"name": "Alex",
"age": 21
}
student["city"] = "Delhi"
print(student)
# {'name': 'Alex', 'age': 21, 'city': 'Delhi'}
🔹 6. Updating Values
If the key already exists, assignment changes its value:
student["age"] = 22
You can also use
.update():student.update({
"age": 23,
"city": "Mumbai"
})
🔹 7. Removing Items
pop() - Removes a specific key and returns its value.student.pop("age")
del removes a specific key:del student["city"]
popitem() - Removes and returns the last inserted key-value pair.student.popitem()
clear() - Removes everything:student.clear()
🔹 8. Checking Whether a Key Exists
Use the
in operator:student = {
"name": "Alex",
"age": 21
}
print("name" in student) # Output: True
Important:
"name" in student checks keys, not values.🔹 9. 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)
This is one of the most commonly used patterns when working with dictionaries.
🔹 10. Dictionary Length
Use
len():student = {
"name": "Alex",
"age": 21,
"course": "Python"
}
print(len(student))
# Output: 3
len() counts the number of key-value pairs.🔹 11. Nested Dictionaries
A dictionary can contain another dictionary.
students = {
"student1": {
"name": "Alex",
"age": 21
},
"student2": {
"name": "Sam",
"age": 22
}
}
print(students["student1"]["name"]) # Output: Alex
Nested dictionaries are extremely common when working with structured data and APIs.
🔹 12. Dictionary Comprehension
