Python Dictionaries
Learn to store and access data using key-value pairs with Python dictionaries.
Dictionaries are one of Python's most powerful built-in data structures. Unlike lists which use numeric indexes, dictionaries let you access values using descriptive keys. This makes your code more readable and your data easier to manage. From configuration files to JSON APIs, dictionaries are used everywhere in real-world Python applications.
📚 Concepts & Theory
What is a Dictionary?
A dictionary is a collection of key-value pairs. Each key is unique and maps to a specific value.
student = {
"name": "Alice",
"age": 20,
"grade": "A"
}
Accessing Values:
print(student["name"]) # Alice
print(student.get("age")) # 20
Adding and Modifying:
student["email"] = "[email protected]" # Add new
student["age"] = 21 # Modify existing
Common Dictionary Methods:
keys()- Get all keysvalues()- Get all valuesitems()- Get key-value pairsget(key, default)- Safe access with defaultpop(key)- Remove and return value
🎯 Your Challenge
Create a dictionary called `book` with three keys: "title" set to "Python Basics", "author" set to "John Smith", and "pages" set to 350. Then add a new key "year" with the value 2024.
📝 Starter Code
# Create the book dictionary
book = {
# Add your key-value pairs here
}
# Add the year key
- Dictionaries use curly braces {}
- Keys and values are separated by colons :
- String keys need quotes
- Use bracket notation to add new keys
Solution
book = {
"title": "Python Basics",
"author": "John Smith",
"pages": 350
}
book["year"] = 2024
Explanation
We create a dictionary using curly braces {} with key-value pairs separated by colons. Keys are strings in quotes, and values can be any data type. To add a new key after creation, we use bracket notation with assignment.
⚠️ Common Mistakes to Avoid
- Using square brackets instead of curly braces for dictionary creation
- Forgetting quotes around string keys
- Using = instead of : inside the dictionary
- Forgetting commas between key-value pairs