In this lesson, you will learn how to use dictionaries to associate unique identifiers with specific data, transforming your ability to look up information efficiently.
Beyond Ordered Sequences
So far, we have relied on lists and tuples to store information. These sequences are perfect for ordered data, but finding a specific item in a large list requires scanning elements one by one. If you have a list of a thousand items, that search becomes slow.
A dictionary (or dict) solves this by acting as an associative array. Instead of searching by numerical index, you map a unique key to a value. Think of it like a physical dictionary: you don't read every word to find a definition; you jump straight to the "key" (the word) to retrieve the "value" (the definition).
Creating and Accessing Mappings
To define a dictionary, you use curly braces {} and separate keys and values with a colon.
# A simple mapping of usernames to their internal IDs
user_database: dict[str, int] = {
"alice": 101,
"bob": 102,
"charlie": 103
}
# Accessing a value via its key
print(user_database["alice"]) # Output: 101
Because dictionaries are designed for direct lookup, they are incredibly fast—even when your dataset grows large. The key acts as a "shortcut" to the memory location of the value.
Rules of the Road
- Uniqueness: Each key must be unique within a dictionary. If you assign a new value to an existing key, you overwrite the old one.
- Hashability: Only immutable types (like strings, integers, or tuples) can be used as keys, because the system needs a fixed identifier to calculate the mapping.
- Flexibility: You can add new entries just as easily as you read them:
user_database["dave"] = 104.
By using key-value pairs, you move from "searching" for data to "addressing" it directly, making your programs significantly more performant and your code much easier to read.
Key Takeaway: Dictionaries provide high-speed data retrieval by mapping unique keys to values, allowing you to access information instantly without iterating through sequences.