๐ Lesson 9: Python Dictionaries – Key-Value Pairs Made Easy
Welcome to Lesson 9! Today we’ll explore dictionaries — a Python data structure that stores information in key-value pairs. Dictionaries are extremely useful for organizing data efficiently.
⭐ What You Will Learn in This Lesson
- How to create and access dictionaries
- Adding, updating, and removing key-value pairs
- Looping through dictionaries
- Practical use cases of dictionaries in Python
๐ฅ Who Is This Lesson For?
- Beginners who want to organize data efficiently
- Students learning Python data structures
- Anyone interested in JSON, APIs, or structured data
๐ฆ What Is a Dictionary?
A dictionary is like a real-life dictionary: each word (key) has a definition (value). In Python, it’s a collection of key-value pairs.
my_dict = {
"name": "Alice",
"age": 25,
"country": "USA"
}
print(my_dict)
๐ง Output
{'name': 'Alice', 'age': 25, 'country': 'USA'}
๐งฉ 1. Accessing Values
Use the key to get its value:
print(my_dict["name"]) # Alice
print(my_dict.get("age")) # 25
๐งฉ 2. Adding or Updating Values
my_dict["profession"] = "Developer" # Add new key-value
my_dict["age"] = 26 # Update existing value
print(my_dict)
๐ง Output
{'name': 'Alice', 'age': 26, 'country': 'USA', 'profession': 'Developer'}
๐งฉ 3. Removing Items
- pop(key) – removes a specific key
- del dict[key] – delete a specific key
- clear() – removes all items
my_dict.pop("country")
del my_dict["profession"]
print(my_dict)
๐ง Output
{'name': 'Alice', 'age': 26}
๐งฉ 4. Looping Through a Dictionary
# Loop through keys
for key in my_dict:
print(key, ":", my_dict[key])
# Loop through key-value pairs
for key, value in my_dict.items():
print(key, "->", value)
๐ง Output
name : Alice
age : 26
name -> Alice
age -> 26
๐งฉ 5. Why Use Dictionaries?
- Store related information together (e.g., a person’s details)
- Fast lookup using keys
- Ideal for JSON, APIs, and structured data
๐งช Practice
- Create a dictionary to store your favorite book’s title, author, and year.
- Add a key for genre and assign a value.
- Update the year of publication.
- Print all keys and values using a loop.
Bonus: Try looping through both keys and values using
items().
❌ Common Mistakes
- Using incorrect keys or spelling mistakes
- Forgetting to use quotes around string keys
- Trying to access a key that doesn’t exist without
get()
❓ Frequently Asked Questions (FAQ)
1. Can dictionary keys be numbers?
Yes! Keys can be strings, numbers, or even tuples (as long as they are immutable).
2. Can I store lists or other dictionaries as values?
Absolutely. Dictionaries can store any type of value.
3. Are dictionaries ordered?
Starting Python 3.7+, dictionaries maintain insertion order.
4. Can I use a key more than once?
No. Each key must be unique. Assigning a value to an existing key updates it.
๐ What’s Next?
In the next lesson, you’ll learn about:
- Sets
- Unique items and membership testing
- Useful set operations
Comments
Post a Comment