🐍intermediate
Python Dictionaries — Key-Value Data
Learn to use Python dictionaries to store and retrieve data using keys — like a real-world dictionary but for code.
What is a Dictionary?
A dictionary stores data as key-value pairs. Think of it like a real dictionary: you look up a word (key) and get its definition (value). In code, you might look up a username and get their profile, or look up a product ID and get its price.
Dictionaries are one of the most used data structures in Python.
Creating & Using Dictionaries
python
# Create a dictionary
student = {
"name": "Ishaan",
"age": 14,
"grade": "9th",
"hobbies": ["coding", "chess"]
}
# Access values
print(student["name"]) # "Ishaan"
print(student.get("age")) # 14
print(student.get("email", "not set")) # "not set" (default)
# Add/update
student["email"] = "ishaan@example.com"
student["age"] = 15
# Delete
del student["grade"]
# Check if key exists
if "name" in student:
print("Name found!")Looping Through Dictionaries
python
scores = {"math": 92, "science": 88, "english": 95}
# Loop through keys
for subject in scores:
print(subject)
# Loop through values
for score in scores.values():
print(score)
# Loop through both
for subject, score in scores.items():
print(f"{subject}: {score}")
# Dictionary comprehension
doubled = {k: v * 2 for k, v in scores.items()}
print(doubled) # {'math': 184, 'science': 176, 'english': 190}Pro Tip
Use .get(key, default) instead of dict[key] when you're not sure if the key exists. dict[key] crashes if the key is missing, but .get() returns a default value instead.
Try It Yourself
Create a dictionary that stores 5 countries and their capitals. Write a function that takes a country name and returns its capital. If the country isn't in the dictionary, return 'Country not found'.
Ready to build?
Put what you learned into practice — pick a project and start coding.
Start Building Free