Python Dictionary Operations and Usage
Dictionary Initialization
A dictionary is a mutable mapping type that stores data as key-value pairs within curly braces {}. It is optimized for fast data lookup.
# Initializing using various methods
inventory = dict(apples=10, oranges=5, bananas=8)
print(inventory)
squares = {n: n*n for n in range(2, 9, 2)}
print(squares)
pairs = dict([('x', 1), ('y', 2)])
print(pairs)
# Empty dictionaries
empty_1 = {}
empty_2 = dict()Keys must be of an immutable type (like strings or numbers) and must be unique. Assigning a value to an existing key overwrites the previous value.
data = {"id": 101, "status": "active", "id": 102}
print(data) # Output will show id: 102Common Dictionary Operations
Assigning a value to a key acts as an insertion if the key is absent, or an update if it exists.
# Inserting and Updating
catalog = {"laptop": 999, "mouse": 25, "keyboard": 50}
catalog["monitor"] = 200 # Insert
catalog["mouse"] = 30 # Update
print(catalog)
# Removing a specific key-value pair
removed_price = catalog.pop("keyboard")
print(f"Removed: {removed_price}")
# Accessing keys, values, and items
print(catalog.keys())
print(catalog.values())
print(catalog.items())
# Safe value retrieval
price = catalog.get("laptop")
missing = catalog.get("webcam") # Returns None instead of KeyError
# Removing the last inserted item
last_item = catalog.popitem()
print(f"Popped: {last_item}")
# Checking size and clearing
print(f"Size: {len(catalog)}")
catalog.clear()
print(catalog)Nested Dictionaries
Values within a dictionary can be other dictionaries, allowing for complex hierarchical data structures.
company = {
"dept_a": {"manager": "Alice", "headcount": 12},
"dept_b": {"manager": "Bob", "headcount": 8}
}
manager_b = company["dept_b"]["manager"]
print(manager_b)Iterating Over Dictionaries
Dictionaries do not support numeric indexing; elements are accessed via their keys. Attempting to access a non-existent key directly (e.g., d[key]) raises a KeyError.
config = {"theme": "dark", "font": 14, "autosave": True}
# Iterating over keys directly
for setting in config:
print(f"Key: {setting}, Value: {config[setting]}")
# Iterating over keys explicitly
for k in config.keys():
print(k)
# Iterating over values
for v in config.values():
print(v)
# Iterating over key-value pairs
for key, val in config.items():
print(f"{key} -> {val}")Key Characteristics
- Capable of storing multiple entries of varying data types.
- Data is stored as unique key-value mappings; duplicate keys overwrite previous entries.
- Elements are accessed via keys rather than sequential index positions.
- Mutable: entries can be added, modified, or removed after creation.
- Iterable using
forloops, but not compatible withwhileloops due to the lack of index support.