Dictionaries
Explanation: A Python dictionary is an unordered collection of data values, used to store data in a key:value pair format. Dictionaries are optimized for retrieving values when the key is known. They are mutable, meaning you can add, remove, and modify key-value pairs after creation. Dictionary keys must be unique and immutable (like strings, numbers, or tuples), while values can be of any data type and can be duplicated. Dictionaries are incredibly versatile for storing structured and associated data.
Defining Dictionaries (Key-Value Pairs)
Explanation: To define a dictionary in Python, you enclose a comma-separated sequence of key: value pairs within curly braces {}
. Each key must be unique and an immutable data type (like strings, numbers, or tuples), while values can be of any data type. An empty dictionary is created using just {}
. Dictionaries provide a powerful way to map unique keys to corresponding values, making data retrieval very efficient.
Note: how to create a dictionary in python, python dictionary syntax, empty dict python, key value pairs python, define dictionary python.
Code Examples:
Python
# Example 1 (Beginner-Friendly): Empty dictionary
# An empty dictionary is often used as a starting point to store data dynamically.
empty_dict = {}
print(f"Empty dictionary: {empty_dict}, Type: {type(empty_dict)}")
# Example 2 (Slightly More Complex): Dictionary with string keys and mixed values
# Common for representing records or objects.
student_profile = {
"name": "Alice",
"age": 20,
"major": "Computer Science",
"is_enrolled": True
}
print(f"Student profile: {student_profile}")
# Example 3 (Intermediate): Dictionary with integer keys
# Keys don't have to be strings; they can be any immutable type.
error_codes = {
200: "OK",
404: "Not Found",
500: "Internal Server Error"
}
print(f"Error codes: {error_codes}")
# Example 4 (Advanced Beginner): Creating a dictionary from a list of tuples (using dict() constructor)
# You can construct a dictionary from an iterable of (key, value) pairs.
# This is useful when data is initially in a list format.
country_capitals_list = [("USA", "Washington D.C."), ("France", "Paris"), ("Japan", "Tokyo")]
country_capitals = dict(country_capitals_list)
print(f"Country capitals from list: {country_capitals}")
# Example 5 (Intermediate): Dictionary with tuple keys (composite keys)
# Since tuples are immutable, they can be used as dictionary keys.
# Useful for representing grid coordinates or multi-part identifiers.
grid_coordinates = {
(0, 0): "Start",
(1, 2): "Obstacle",
(3, 3): "End"
}
print(f"Grid coordinates dictionary: {grid_coordinates}")
# Example 6 (Advanced): Nested dictionaries
# Dictionaries can contain other dictionaries as values, allowing for complex hierarchical data.
company_data = {
"employees": {
"EMP001": {"name": "Bob", "department": "HR", "salary": 60000},
"EMP002": {"name": "Carol", "department": "IT", "salary": 75000}
},
"locations": ["New York", "London"]
}
print(f"Company data (nested dict): {company_data}")
print(f"Bob's department: {company_data['employees']['EMP001']['department']}")
# Example 7 (Advanced): Using fromkeys() method
# Creates a new dictionary with keys from an iterable and values set to a default.
default_status = "Pending"
user_ids = ["userA", "userB", "userC"]
initial_tasks = dict.fromkeys(user_ids, default_status)
print(f"Initial tasks with default status: {initial_tasks}")
Accessing Values
Explanation: To access a value in a Python dictionary, you use its corresponding key enclosed in square brackets []
. This is the most common way to retrieve dictionary values. If you try to access a key that doesn't exist, it will raise a KeyError
. Understanding how to get data from dictionary is fundamental for working with this data structure.
Note: python access dictionary value, get dictionary element, dictionary key error, retrieve value from dict python, python dict lookup.
Code Examples:
Python
# Initial dictionary for demonstration
student_grades = {
"Alice": 95,
"Bob": 88,
"Charlie": 72,
"David": 91
}
print(f"Student grades: {student_grades}")
# Example 1 (Beginner-Friendly): Accessing value using square brackets
# Directly get the value associated with a known key.
alice_grade = student_grades["Alice"]
print(f"Alice's grade: {alice_grade}") # Output: 95
# Example 2 (Slightly More Complex): Accessing value with a variable key
# Keys can be variables, which makes dynamic lookups possible.
student_name = "Bob"
bob_grade = student_grades[student_name]
print(f"{student_name}'s grade: {bob_grade}") # Output: 88
# Example 3 (Intermediate): Handling KeyError (attempting to access non-existent key)
# It's important to anticipate and handle cases where a key might not exist.
non_existent_student = "Eve"
try:
eve_grade = student_grades[non_existent_student]
print(f"{non_existent_student}'s grade: {eve_grade}")
except KeyError as e:
print(f"Error: Could not find grade for '{e}'.") # Output: Error: Could not find grade for ''Eve''.
# Example 4 (Advanced Beginner): Using the .get() method (safer access)
# The .get() method returns None (or a specified default value) if the key is not found,
# instead of raising a KeyError.
charlie_grade = student_grades.get("Charlie")
print(f"Charlie's grade (using .get()): {charlie_grade}") # Output: 72
eve_grade_safe = student_grades.get("Eve", "N/A") # Provide a default value
print(f"Eve's grade (using .get() with default): {eve_grade_safe}") # Output: N/A
# Example 5 (Intermediate): Accessing values in nested dictionaries
# Chain square brackets to navigate through nested dictionaries.
company_structure = {
"HR": {"manager": "Anna", "employees": ["Ben", "Chloe"]},
"IT": {"manager": "Daniel", "employees": ["Emily", "Frank"]}
}
it_manager = company_structure["IT"]["manager"]
hr_employee = company_structure["HR"]["employees"][0]
print(f"\nIT Manager: {it_manager}") # Output: Daniel
print(f"HR Employee: {hr_employee}") # Output: Ben
# Example 6 (Advanced): Conditional access for complex data structures
# Combine .get() with checks for robustness.
product_info = {
"Laptop": {"price": 1200, "stock": 50, "features": ["fast CPU", "lightweight"]},
"Keyboard": {"price": 75, "stock": 100}
}
# Safely try to get features for 'Laptop'
laptop_features = product_info.get("Laptop", {}).get("features", [])
print(f"Laptop features: {laptop_features}") # Output: ['fast CPU', 'lightweight']
# Safely try to get features for 'Monitor' (which doesn't exist)
monitor_features = product_info.get("Monitor", {}).get("features", [])
print(f"Monitor features: {monitor_features}") # Output: []
# Example 7 (Advanced): Using 'in' operator before accessing (for explicit error handling)
# Check for key existence first, then access if present.
item_to_check = "David"
if item_to_check in student_grades:
print(f"Grade for {item_to_check} is: {student_grades[item_to_check]}")
else:
print(f"'{item_to_check}' not found in student grades.")
Adding, Modifying, and Deleting Key-Value Pairs
Explanation: Since Python dictionaries are mutable, you can easily add new entries, modify existing values, and delete key-value pairs after a dictionary has been created. Adding a new pair is done by assigning a value to a new key. Modifying an existing value is done by assigning a new value to an existing key. Deleting can be done using the del
keyword or methods like pop()
. Mastering Python dictionary operations is crucial for dynamic data management.
Note: add item to dictionary python, change dictionary value python, delete entry from dictionary, remove key from dict python, update dictionary python.
Code Examples:
Python
# Initial dictionary for demonstration
inventory = {
"apples": 50,
"bananas": 100,
"oranges": 75
}
print(f"Initial Inventory: {inventory}")
# Example 1 (Beginner-Friendly): Adding a new key-value pair
# Assign a value to a new key.
inventory["grapes"] = 120 # 'grapes' key didn't exist, so it's added.
print(f"After adding 'grapes': {inventory}") # Output: {'apples': 50, 'bananas': 100, 'oranges': 75, 'grapes': 120}
# Example 2 (Slightly More Complex): Modifying an existing value
# Assign a new value to an existing key.
inventory["apples"] = 60 # 'apples' key already exists, so its value is updated.
print(f"After modifying 'apples' count: {inventory}") # Output: {'apples': 60, 'bananas': 100, 'oranges': 75, 'grapes': 120}
# Example 3 (Intermediate): Deleting a key-value pair using del
# The 'del' keyword permanently removes a key and its associated value.
# Raises KeyError if the key does not exist.
del inventory["oranges"]
print(f"After deleting 'oranges': {inventory}") # Output: {'apples': 60, 'bananas': 100, 'grapes': 120}
# del inventory["non_existent_fruit"] # Would raise KeyError
# Example 4 (Advanced Beginner): Removing a key-value pair using pop()
# The .pop(key) method removes the specified key and returns its value.
# It's safer than 'del' because it can take a default value to return if the key is not found.
removed_bananas_count = inventory.pop("bananas")
print(f"After popping 'bananas': {inventory}, Removed count: {removed_bananas_count}") # Output: {'apples': 60, 'grapes': 120}, Removed count: 100
# Try popping a non-existent key with a default return value
non_existent_pop = inventory.pop("kiwis", 0)
print(f"Attempted pop for 'kiwis': {non_existent_pop}, Inventory: {inventory}") # Output: Attempted pop for 'kiwis': 0, Inventory: {'apples': 60, 'grapes': 120}
# Example 5 (Intermediate): Updating multiple key-value pairs using update()
# The .update() method merges a dictionary (or an iterable of key-value pairs) into the current dictionary.
# If keys exist, their values are updated; if not, new pairs are added.
new_stock = {"grapes": 150, "pears": 80, "apples": 70}
inventory.update(new_stock)
print(f"After update with new stock: {inventory}") # Output: {'apples': 70, 'grapes': 150, 'pears': 80}
# Example 6 (Advanced): Using setdefault() for adding with a default only if key is missing
# The .setdefault(key, default_value) method returns the value for 'key' if key exists.
# If 'key' does not exist, it inserts 'key' with 'default_value' and returns that default_value.
status_track = {"task1": "completed", "task2": "in_progress"}
print(f"\nInitial status: {status_track}")
# 'task1' already exists, its value is returned, dictionary remains unchanged.
task1_status = status_track.setdefault("task1", "pending")
print(f"Status for task1 (already exists): {task1_status}, Dict: {status_track}") # Output: completed, Dict: {'task1': 'completed', 'task2': 'in_progress'}
# 'task3' does not exist, it's added with "new", and "new" is returned.
task3_status = status_track.setdefault("task3", "new")
print(f"Status for task3 (new): {task3_status}, Dict: {status_track}") # Output: new, Dict: {'task1': 'completed', 'task2': 'in_progress', 'task3': 'new'}
# Example 7 (Advanced): Clearing all items from a dictionary using clear()
# The .clear() method removes all items from the dictionary.
config_settings = {"theme": "dark", "notifications": True, "language": "en"}
print(f"\nBefore clear: {config_settings}")
config_settings.clear()
print(f"After clear: {config_settings}") # Output: {}
Dictionary Methods (keys(), values(), items(), get(), pop(), update())
Explanation: Python dictionaries come with several built-in dictionary methods that provide convenient ways to interact with their contents. These methods allow you to retrieve all keys, all values, or all key-value pairs; safely get values; remove elements; and merge dictionaries. They are fundamental for effective Python dictionary manipulation.
Note: python dict keys, python dict values, python dict items, python dict get, python dict pop, python dict update, dictionary methods tutorial.
Code Examples:
Python
# Initial dictionary for demonstration
product = {
"name": "Laptop",
"price": 1200,
"category": "Electronics",
"in_stock": True,
"weight_kg": 1.8
}
print(f"Initial Product Dictionary: {product}")
# Example 1 (Beginner-Friendly): .keys() - Get all keys
# Returns a view object that displays a list of all the keys in the dictionary.
all_keys = product.keys()
print(f"All keys: {list(all_keys)}") # Convert to list for display: ['name', 'price', 'category', 'in_stock', 'weight_kg']
# Example 2 (Slightly More Complex): .values() - Get all values
# Returns a view object that displays a list of all the values in the dictionary.
all_values = product.values()
print(f"All values: {list(all_values)}") # Convert to list for display: ['Laptop', 1200, 'Electronics', True, 1.8]
# Example 3 (Intermediate): .items() - Get all key-value pairs
# Returns a view object that displays a list of a dictionary's key-value tuple pairs.
all_items = product.items()
print(f"All items: {list(all_items)}") # Convert to list for display: [('name', 'Laptop'), ('price', 1200), ...]
# Example 4 (Advanced Beginner): .get(key, default) - Safe value access
# Returns the value for the specified key. If the key is not found, it returns the default value (None if not specified).
product_name = product.get("name")
product_material = product.get("material", "Plastic/Metal") # Key 'material' doesn't exist, returns default
print(f"Product name (using .get()): {product_name}")
print(f"Product material (using .get() with default): {product_material}")
# Example 5 (Intermediate): .pop(key, default) - Remove and return value
# Removes the item with the specified key and returns its value.
# If the key is not found, it returns the default value if provided, else raises KeyError.
removed_category = product.pop("category")
print(f"After pop('category'): {product}, Removed category: {removed_category}") # Output: Removed category: Electronics
# Example 6 (Advanced): .update(other_dict) - Merge dictionaries
# Updates the dictionary with the elements from another dictionary object or from an iterable of key/value pairs.
# Existing keys are updated, new keys are added.
new_details = {"price": 1250, "warranty_years": 2, "in_stock": False}
product.update(new_details)
print(f"After update with new details: {product}") # 'price' and 'in_stock' updated, 'warranty_years' added.
# Example 7 (Advanced): .popitem() - Remove and return an arbitrary (key, value) pair
# Removes and returns an arbitrary (key, value) pair from the dictionary.
# Useful for destructive iteration or processing items one by one without knowing keys.
# Raises KeyError if the dictionary is empty.
print(f"\nBefore popitem: {product}")
if product: # Check if dictionary is not empty before popping
arbitrary_item_key, arbitrary_item_value = product.popitem()
print(f"Popped item: Key='{arbitrary_item_key}', Value='{arbitrary_item_value}'")
print(f"After popitem: {product}")
else:
print("Dictionary is empty, cannot popitem.")
Dictionary Comprehensions
Explanation: Python dictionary comprehensions provide a concise and efficient way to create new dictionaries based on existing iterables or by transforming other dictionaries. Similar to list comprehensions, they allow you to define key-value pairs using an expression for each item, optionally filtering items based on a condition. They are a powerful feature for Pythonic dictionary creation and data transformation.
Note: python dict comprehension tutorial, create dictionary concisely, filter dictionary python, transform dict python, python one-liner dict.
Code Examples:
Python
# Example 1 (Beginner-Friendly): Basic dictionary comprehension (from lists)
# Creates a dictionary mapping numbers to their squares.
# Syntax: {key_expression: value_expression for item in iterable}
numbers = [1, 2, 3, 4, 5]
squares_dict = {num: num**2 for num in numbers}
print(f"Squares Dictionary: {squares_dict}") # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Example 2 (Slightly More Complex): Dictionary comprehension with conditional filtering
# Creates a dictionary of only even numbers mapped to their squares.
# Syntax: {key_exp: value_exp for item in iterable if condition}
even_squares = {num: num**2 for num in range(10) if num % 2 == 0}
print(f"Even Squares Dictionary: {even_squares}") # Output: {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
# Example 3 (Intermediate): Inverting a dictionary (swapping keys and values)
# Assuming values are unique and hashable (immutable) to be valid keys.
original_dict = {"apple": 1, "banana": 2, "cherry": 3}
inverted_dict = {value: key for key, value in original_dict.items()}
print(f"Inverted Dictionary: {inverted_dict}") # Output: {1: 'apple', 2: 'banana', 3: 'cherry'}
# Example 4 (Advanced Beginner): Creating dictionary from two lists (using zip)
# Combines elements from two lists into key-value pairs.
fruits = ["apple", "banana", "cherry"]
prices = [1.0, 0.5, 1.5]
fruit_prices = {fruit: price for fruit, price in zip(fruits, prices)}
print(f"Fruit Prices: {fruit_prices}") # Output: {'apple': 1.0, 'banana': 0.5, 'cherry': 1.5}
# Example 5 (Intermediate): Conditional value assignment
# Assigns different values based on a condition.
# Syntax: {key_exp: value_if_true if condition else value_if_false for item in iterable}
temperatures_c = {"cityA": 28, "cityB": 15, "cityC": 32, "cityD": 5}
weather_status = {
city: "Hot" if temp > 25 else ("Cold" if temp < 10 else "Mild")
for city, temp in temperatures_c.items()
}
print(f"Weather Status: {weather_status}") # Output: {'cityA': 'Hot', 'cityB': 'Mild', 'cityC': 'Hot', 'cityD': 'Cold'}
# Example 6 (Advanced): Nested dictionary comprehension (for complex data transformations)
# Creating a nested dictionary where inner keys are lengths of words.
text_data = ["hello", "world", "python", "code", "ai"]
nested_word_lengths = {
word: {char: len(word) for char in word} for word in text_data
}
print(f"Nested Word Lengths: {nested_word_lengths}")
# Output: {'hello': {'h': 5, 'e': 5, 'l': 5, 'o': 5}, ...} (each char mapped to parent word length)
# Example 7 (Advanced): Filtering and restructuring existing dictionaries
# Create a new dictionary containing only employees with salary > 70000.
employee_data = {
"EMP001": {"name": "Alice", "salary": 65000, "dept": "HR"},
"EMP002": {"name": "Bob", "salary": 80000, "dept": "IT"},
"EMP003": {"name": "Charlie", "salary": 72000, "dept": "Finance"}
}
high_earners = {
emp_id: {"name": details["name"], "salary": details["salary"]}
for emp_id, details in employee_data.items() if details["salary"] > 70000
}
print(f"High Earners: {high_earners}")
# Output: {'EMP002': {'name': 'Bob', 'salary': 80000}, 'EMP003': {'name': 'Charlie', 'salary': 72000}}