Dictionary
A dictionary stores data in key-value pairs. Keys must be unique and immutable (string, number, tuple), while values can be of any data type.
Dictionaries are very useful when you need to map information with clear labels, not just numeric indices. For example, storing user profile data, application configuration, or database query results. Because lookups are done using keys (not indices), data access operations in dictionaries are very fast — average-case complexity O(1).
Python also provides various built-in methods to manipulate dictionaries, such as .keys(), .values(), .items(), .update(), and .pop(). Dictionary comprehensions allow creating dictionaries concisely in one line, similar to list comprehensions.
Code Example
# Creating a dictionary
student = {
"name": "John",
"age": 20,
"major": "Computer Science"
}
# Accessing values
print(student["name"]) # John
print(student.get("gpa", 0.0)) # 0.0 (default)
# Modifying
student["age"] = 21
student["gpa"] = 3.85
# Iteration
for key, value in student.items():
print(f"{key}: {value}")
# Dict Comprehension
squares = {x: x**2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
Code Explanation
- Creating a dictionary: Curly braces
{}containkey: valuepairs. The key"name"is mapped to the value"John". - Accessing values:
student["name"]returns the value of the key"name". The.get("gpa", 0.0)method is safe to use because it returns the default value0.0if the key is not found, without raising an error. - Modifying: Assigning a value to an existing key updates its value. Assigning to a new key adds a new pair to the dictionary.
- Iteration:
.items()returns(key, value)pairs. Thefor key, value in ...loop performs unpacking directly. - Dictionary comprehension:
{x: x**2 for x in range(5)}creates a dictionary with keys 0–4 and values being their squares.
Everyday Example
An online store wants to keep track of product inventory. Each product has a unique code (key) and detailed information (value as a dictionary).
store_stock = {
"BRG001": {"name": "Laptop", "price": 12000000, "stock": 5},
"BRG002": {"name": "Mouse", "price": 150000, "stock": 20},
"BRG003": {"name": "Keyboard", "price": 350000, "stock": 10}
}
code = "BRG001"
if code in store_stock:
item = store_stock[code]
print(f"{item['name']} - ${item['price']:,} ({item['stock']} left)")
# Output: Laptop - $12,000,000 (5 left)
Summary
Dictionaries are the most flexible data structure in Python for storing labeled data. O(1) access speed, support for various built-in methods, and dictionary comprehensions make them the top choice for structured data. Use dictionaries when you need to map information with meaningful keys.