Dictionaries as Key-Value Maps
Explore how Python dictionaries function as key-value maps to store and access data by labels instead of positions. Learn to create, update, and check dictionaries with safe methods. Understand iteration techniques over keys, values, and items to handle complex data structures efficiently.
As studied earlier, lists are excellent for ordered sequences, but they have a major limitation: we must know the exact position (index) of an item to retrieve it. If we want to store a user’s profile, remembering that their email is at index 2 and their username is at index 0 is error-prone and hard to read. We need a data structure that lets us label our data.
We use Python dictionaries to map unique labels (also called keys) to specific values, allowing us to look up information by name. This structure makes it easy to represent a single object with multiple named attributes, such as a product in an inventory, where each attribute (e.g., name, price, quantity) is accessed directly through its corresponding key.
Defining a dictionary
A dictionary is a collection of key-value pairs. When learning how to create a dictionary in Python, the most common method is using curly braces {}, separating keys and values with a colon :.
Unlike lists, dictionaries are unordered in terms of access (though Python 3.7+ preserves insertion order for display). We do not access items by position; we access them by their key.
Keys must be unique and immutable (usually strings or numbers).
Values can be any type: strings, integers, lists, or even other dictionaries.
We use dictionaries when we need to describe a single object with multiple named attributes, such as a product in an inventory.
Let’s see an example below:
Lines 2–7: We create a dictionary named
product. Each line inside the braces defines a pair: the key (on the left of the colon) and the value (on the right of the colon).Keys:
"name","price","in_stock", and"sku".Values:
"Mechanical Keyboard",89.99,True, and"KB-101".
Line 9: We print the entire dictionary structure.
Line 10: We verify that the type is
dict.
Looking up data
To retrieve a value, we place the key inside square brackets [] immediately after the dictionary name. This is similar to accessing a list by index, but we use the meaningful label instead of a number.
Line 4: We look up the value associated with the key
"name"("Mechanical Keyboard") and assign it toproduct_name.Line 5: We look up the value for
"price"(89.99) and assign it toproduct_price.Line 7: We use the retrieved variables in an f-string to print the values.
If we try to access a key that does not exist, Python raises a KeyError. This strict behavior ensures we don't accidentally work with missing data. Try accessing product[brand] in the above code, and notice the output.
Inserting and updating data
Dictionaries are mutable, which means their contents can be modified after creation. Python uses the same square bracket syntax, dict[key] = value, for both adding new key–value pairs and updating existing ones.
If the specified key already exists, Python updates the associated value.
If the specified key does not exist, Python creates a new key–value pair and adds it to the dictionary.
This behavior allows dictionaries to be extended and modified dynamically as needed.
Line 4: The key
"theme"exists, so its value is updated from"light"to"dark".Line 7: The key
"language"does not exist, so Python adds a new pair,"language": "English", to the dictionary.Line 9: We print the dictionary to see both changes.
Checking for keys
Because attempting to access a nonexistent key in a dictionary raises a KeyError, it is often necessary to verify that a key exists before reading its value.
Python provides the in operator for this purpose, which returns True if the key is present in the dictionary and False otherwise. This provides safe, predictable access to dictionary data.
Line 3: We define a target key
"oranges"that is present in the dictionary.Line 5: The expression
item in inventoryevaluates toTrue, and line 6 executes, changing the values of"oranges"to 10.Line 8: We print the dictionary to notice the output.
Now, try changing the target value (at line 3) to "bananas". This time, line 5 evaluates to False and line 6 will get skipped.
How to iterate over a dictionary in Python
When we loop over a dictionary using a standard for loop, Python iterates over the keys by default. Since we have the key, we can use the [] operator inside the loop to retrieve the corresponding value (e.g., dictionary[key]).
However, Python provides specific methods to make iteration clearer depending on what data we need:
.keys(): Returns keys (default behavior)..values(): Returns only the values..items(): Returns pairs of(key, value), which allows us to access both variables directly without using[].
Line 4: We call
scores.items(), which provides a view of pairs like("Alice", 88). We unpack these into the variablesstudent(key) andscore(value).Line 5: We use both variables inside the loop to print a formatted message.
While dictionaries allow us to map labels to values, sometimes we only care about the existence of unique items without needing a specific label or value attached to them. In the next lesson, we will explore Python sets, which are unordered collections of unique elements. We will learn how to use a set in Python to efficiently handle tasks like removing duplicates from a list, performing mathematical unions, and checking for membership with incredible speed.