Concept Explanation
In a standard list, you find items by their position (0, 1, 2...). But in a Dictionary, you find items by a Key. It works exactly like a real-life dictionary: you look up a word (the Key) to find its definition (the Value).
Dictionaries are unordered (in older Python versions) or ordered (in Python 3.7+), but they are primarily designed for fast lookups. They are mutable, meaning you can add, remove, and change entries. Every entry in a dictionary is a pair: key: value.
Syntax or Core Structure
Creating a Dictionary
Dictionaries use curly braces {} and colons : to separate keys from values.
# Creation
car = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
# Accessing Values
print(car["brand"]) # "Ford"
# Using the .get() method (Safer!)
# If the key doesn't exist, this returns 'None' instead of crashing.
print(car.get("color", "Not Specified"))
Common Dictionary Methods
.keys(): Returns a list of all names (keys)..values(): Returns a list of all data (values)..items(): Returns the pairs as tuples—useful for looping!.update({"key": "value"}): Adds or updates multiple entries at once..pop("key"): Removes the specific entry and returns its value.
Code Example #1 (Basic)
Updating and adding new information to a profile.
student = {
"name": "Alice",
"grade": "A",
"courses": ["Math", "Physics"]
}
# Update the grade
student["grade"] = "A+"
# Add a missing field
student["graduated"] = False
# Deleting a field
del student["courses"]
print(f"Updated student profile: {student}")
Code Example #2 (Intermediate)
Looping through a dictionary to generate a report.
inventory = {
"apples": 50,
"bananas": 120,
"cherries": 15
}
print("--- Inventory Report ---")
for fruit, count in inventory.items():
if count < 20:
status = "LOW STOCK!"
else:
status = "OK"
print(f"{fruit.capitalize()}: {count} ({status})")
Real World Example
Dictionaries are the foundation of JSON (JavaScript Object Notation), which is the primary way data is sent across the internet. If you fetch a user's profile from an API, it will arrive as a dictionary-like structure.
# 👤 API Response Simulation
api_response = {
"status": 200,
"data": {
"user_id": 105,
"username": "coder_pro",
"preferences": {
"dark_mode": True,
"notifications": False
}
}
}
# Navigating nested dictionaries
user_name = api_response["data"]["username"]
is_dark_mode = api_response["data"]["preferences"]["dark_mode"]
print(f"User: {user_name} | Theme: {'Dark' if is_dark_mode else 'Light'}")
Common Mistakes
- KeyError: Trying to access
my_dict["wrong_key"]. If the key isn't there, Python crashes. Use.get()to avoid this. - Duplicate Keys: You cannot have two keys with the same name. If you write
{"name": "Alice", "name": "Bob"}, Python will simply overwrite Alice with Bob. - Using Mutable Keys: Keys must be "hashable" (immutable). You can use strings, numbers, or tuples as keys—but you cannot use a List as a key.
Best Practices
- Consistent Keys: Even though Python allows it, don't mix the types of your keys (e.g., some as numbers and some as strings). Keep them consistent so your loops don't break.
- Clear Naming: Since keys act as documentation, name them clearly.
"u_id"is okay, but"user_id"is much better for anyone reading your code later.
Practice Exercises
- The Contact Book: Create a dictionary called
contactswith 3 names as keys and 3 phone numbers as values. Add a 4th contact. Change one of the existing phone numbers. - Word Counter: Create a string: "apple banana apple cherry banana apple". Use a dictionary to count how many times each word appears. (Hint: Loop through a list of the words).
- The Nesting Challenge: Create a dictionary representing a
Library. The keys should be Category names ("Fiction", "Science"), and the values should be Lists of book titles in that category.