By the end of this lesson, you will be able to create, access, and modify Python dictionaries to store and retrieve data efficiently using key-value pairs.
What it is
A dictionary in Python is a built-in data structure that stores data as key-value pairs. Unlike lists, which use integer indices, dictionaries use unique keys (usually strings or numbers) to map directly to values. Think of it like a physical dictionary: you look up a word (the key) to find its definition (the value). This structure allows for extremely fast data retrieval because Python uses hashing internally to locate items without scanning through every element.
Key terms include:
key: The unique identifier used to look up a value.value: The data associated with a specific key.hashable: A property required for keys; most immutable types (strings, integers, tuples) are hashable, while mutable types (lists, other dicts) are not.
Why it matters
- Fast Lookups: Accessing a value by its key takes constant time O(1), regardless of the dictionary size.
- Structured Data: Ideal for representing objects, configuration settings, or JSON-like data structures.
- Flexibility: Values can be any data type, including other dictionaries or lists, allowing for nested structures.
- Readability: Code becomes more self-documenting when using descriptive keys instead of magic numbers or indices.
Syntax or steps
Dictionaries are defined using curly braces {} with colon-separated key-value pairs. Items are separated by commas.
my_dict = {"key1": "value1", "key2": "value2"}
To access a value, use square brackets with the key: my_dict["key1"]. To add or update an item, assign a value to a key: my_dict["new_key"] = "new_value".
Example
The following example creates a student record, accesses data, updates a grade, and adds a new field.
# Create a dictionary
student = {
"name": "Alice",
"age": 20,
"grades": [85, 90, 78]
}
# Access a value
print(student["name"]) # Output: Alice
# Update an existing value
student["age"] = 21
# Add a new key-value pair
student["major"] = "Computer Science"
# Check if a key exists before accessing to avoid errors
if "gpa" in student:
print(student["gpa"])
else:
print("GPA not recorded yet.")
print(student)
Explanation: First, we initialize student with three keys. We retrieve "name" directly. Then, we overwrite the "age" value. Next, we insert a completely new key "major". Finally, we use the in operator to safely check for the existence of "gpa" before trying to print it, preventing a KeyError.
Common mistakes
- Using unhashable keys: You cannot use a list or another dictionary as a key. Use tuples instead if you need composite keys.
- Assuming order: While modern Python (3.7+) preserves insertion order, do not rely on alphabetical sorting unless explicitly done via
sorted(). - Accessing missing keys: Using
dict[key]raises aKeyErrorif the key doesn't exist. Usedict.get(key)to returnNoneor a default value instead. - Mutating during iteration: Do not add or remove keys while looping over the dictionary. Iterate over a copy (
list(dict.keys())) if modifications are needed.
When to use it
Compare dictionaries with lists based on how you need to access data.
| Feature | List | Dictionary |
|---|---|---|
| Access Method | Index-based (0, 1, 2...) | Key-based ("name", "id"...) |
| Lookup Speed | O(n) for search by value | O(1) for lookup by key |
| Best For | Ordered collections of similar items | Mapping relationships or named attributes |
Use a list when order matters and you access items by position. Use a dictionary when you need to associate labels with data or perform frequent lookups by name/ID.
Practice
Guided Exercise: Create a dictionary called prices containing three fruits and their costs. Print the price of one fruit, then update the price of another.
Challenge: Write a script that counts the frequency of each letter in the string "hello world" using a dictionary. Hint: Initialize empty dict, loop through characters, check if char is in dict, increment count or set to 1.
Quick check
Question: What happens if you try to access a key that does not exist in a dictionary using square bracket notation?
Answer: It raises a KeyError exception, stopping program execution unless handled with try/except or checked beforehand.
Summary
Python dictionaries provide a powerful way to store data as key-value pairs, enabling fast lookups and structured organization. Mastering methods like get(), keys(), and safe access patterns ensures robust code when managing complex data mappings.