Lesson 8.1: Creating and Using Dictionaries
What You'll Learn
- What dictionaries are and why they are useful
- How to create dictionaries with key-value pairs
- How to access values using keys
- How to add, update, and delete key-value pairs
- How to handle missing keys with
get()and avoidKeyError - How to check if a key exists in a dictionary
1. What is a Dictionary?
A dictionary is a collection of key-value pairs. Think of it like a real dictionary: you look up a word (the key) and get a definition (the value). In Python, you can look up any key and get the value associated with it.
{} or the dict() constructor.
Unlike lists, which use numeric indices (0, 1, 2...), dictionaries use meaningful keys to organize data:
# A list uses numeric indices student_list = ["Alice", 20, "Computer Science"] # What does index 1 mean? Hard to tell! # A dictionary uses descriptive keys student_dict = { "name": "Alice", "age": 20, "major": "Computer Science" } # Much clearer what each value represents!
2. Creating Dictionaries
There are several ways to create a dictionary in Python:
Using Curly Braces (Most Common)
# Empty dictionary empty = {} # Dictionary with key-value pairs person = { "name": "Maria", "age": 25, "city": "Los Angeles" } print(person) print(type(person))
Using the dict() Constructor
# Using keyword arguments person = dict(name="Maria", age=25, city="Los Angeles") # From a list of tuples colors = dict([("red", "#FF0000"), ("green", "#00FF00")]) print(person) print(colors)
# Keys must be unique - last value wins grades = {"math": 90, "math": 95} print(grades) # {'math': 95} - the 90 is overwritten # Values can be any type mixed = { "name": "Bob", "scores": [85, 92, 78], "passed": True, "gpa": 3.5 }
3. Accessing Values
You access dictionary values by placing the key inside square brackets:
student = {
"name": "Carlos",
"age": 22,
"major": "Biology"
}
print(student["name"])
print(student["age"])
print(student["major"])
KeyError: When a Key Doesn't Exist
If you try to access a key that does not exist, Python raises a KeyError:
student = {"name": "Carlos", "age": 22}
# This will cause a KeyError!
print(student["gpa"])
The get() Method: Safe Access
The get() method returns None (or a default value you choose) instead of raising an error:
student = {"name": "Carlos", "age": 22}
# Returns None if key doesn't exist
print(student.get("gpa"))
# You can provide a default value
print(student.get("gpa", 0.0))
# Works normally for keys that exist
print(student.get("name"))
When to Use get() vs Square Brackets
Use square brackets dict[key] when you are certain the key exists and want an error if it does not (a bug you want to catch early).
Use get() when the key might not exist and you want to handle that gracefully with a default value.
4. Adding and Updating Entries
Dictionaries are mutable, so you can add new key-value pairs or change existing values at any time:
profile = {"name": "Dana"}
# Add new keys
profile["age"] = 28
profile["email"] = "dana@example.com"
print(profile)
# Update existing key
profile["age"] = 29
print(profile)
The syntax is the same for adding and updating. Python checks: if the key already exists, it updates the value. If the key is new, it adds the pair.
5. Removing Entries
There are several ways to remove key-value pairs from a dictionary:
inventory = {
"apples": 5,
"bananas": 3,
"oranges": 8,
"grapes": 12
}
# del removes a key-value pair
del inventory["bananas"]
print(inventory)
# pop() removes and returns the value
count = inventory.pop("oranges")
print(f"Removed oranges: {count}")
print(inventory)
# pop() with default avoids KeyError
count = inventory.pop("mangoes", 0)
print(f"Removed mangoes: {count}")
6. Checking if a Key Exists
Use the in keyword to check whether a key exists in a dictionary:
menu = {
"coffee": 3.50,
"tea": 2.75,
"water": 1.00
}
print("coffee" in menu)
print("juice" in menu)
print("juice" not in menu)
# Common pattern: check before accessing
item = "coffee"
if item in menu:
print(f"{item} costs ${menu[item]:.2f}")
else:
print(f"Sorry, {item} is not on the menu")
in operator checks keys, not values. To check if a value exists, use value in dict.values().
Check Your Understanding
Question: What will the following code print?
info = {"x": 10, "y": 20}
info["z"] = 30
info["x"] = 99
print(len(info))
print(info.get("w", 0))
Answer:
3 — the dictionary has keys "x", "y", and "z" (updating "x" does not add a new key).
0 — key "w" does not exist, so get() returns the default value 0.
Try It Yourself
Create a dictionary called contact with keys "name", "phone", and "email". Then:
- Print the person's name
- Add a
"city"key - Update the phone number
- Use
get()to safely access a"website"key with a default of"N/A"
Key Takeaways
- Dictionaries store data as key-value pairs using curly braces
{} - Keys must be immutable and unique; values can be any type
- Access values with
dict[key](raisesKeyErrorif missing) ordict.get(key, default)(returns a default instead) - Add or update entries with
dict[key] = value - Remove entries with
del dict[key]ordict.pop(key) - Check for keys with
key in dict