Python Dictionaries
🐍 Python Dictionaries — Full Tutorial
A dictionary in Python is an unordered, changeable, and indexed collection that stores key-value pairs.
Keys must be unique and immutable (strings, numbers, tuples).
Values can be of any data type.
1. Creating a Dictionary
2. Accessing Values
You can access dictionary values by keys:
✅ Using .get() avoids errors if the key does not exist:
3. Modifying Dictionary Items
You can update values by key:
Add a new key-value pair:
4. Removing Items
| Method | Description |
|---|---|
pop(key) | Removes item with the given key |
popitem() | Removes the last inserted item |
del dict[key] | Deletes a key-value pair |
clear() | Empties the dictionary |
Example:
5. Looping Through Dictionaries
1️⃣ Loop through keys:
2️⃣ Loop through values:
3️⃣ Loop through key-value pairs:
6. Dictionary Methods
| Method | Description |
|---|---|
keys() | Returns all keys |
values() | Returns all values |
items() | Returns all key-value pairs as tuples |
copy() | Returns a shallow copy |
update() | Updates dictionary with another dict or key-value pairs |
Example:
7. Nested Dictionaries
A dictionary can contain other dictionaries:
8. Dictionary Comprehension (Advanced)
9. Checking if a Key Exists
10. Merging Dictionaries
Python 3.9+ allows using | operator:
Or using update():
⭐ Mini Example: Student Info
🧠 Summary
| Feature | Dictionary |
|---|---|
| Collection Type | Key-value pairs |
| Ordered | Python 3.7+ |
| Mutable | ✅ Yes |
| Duplicates | Keys ❌ No, Values ✅ Yes |
| Access | dict[key] or dict.get(key) |
📝 Practice Exercises
Create a dictionary of 3 students with name, age, and course.
Update one student’s age and add a new key
city.Loop through all students and print name and course.
Merge two dictionaries of student marks.
Use dictionary comprehension to create
{1:1, 2:4, 3:9, 4:16}.
