Python Dictionary Methods
Master key-value pair operations with dictionary methods
📚 Working with Dictionaries
Dictionaries store data in key-value pairs. They're perfect for organizing related information and fast lookups.
# Basic dictionary operations
person = {"name": "Alice", "age": 25}
person["city"] = "New York" # Add new key-value
print(person) # {'name': 'Alice', 'age': 25, 'city': 'New York'}
Dictionary Method Categories
Accessing Data
Get values and check keys
Modifying Data
Update and change dictionary content
Removing Data
Delete keys and clear dictionary
Copying Data
Create dictionary copies
🔹 Accessing Dictionary Data
get() - Safe Value Access
Gets a value without causing errors if key doesn't exist
student = {"name": "Bob", "grade": "A"}
# Safe way to get values
name = student.get("name")
print(name) # Bob
# Get with default value
age = student.get("age", "Unknown")
print(age) # Unknown
keys(), values(), items() - Get All Data
Access all keys, values, or key-value pairs
colors = {"red": "#FF0000", "green": "#00FF00"}
# Get all keys
print(list(colors.keys())) # ['red', 'green']
# Get all values
print(list(colors.values())) # ['#FF0000', '#00FF00']
# Get all key-value pairs
print(list(colors.items())) # [('red', '#FF0000'), ('green', '#00FF00')]
🔹 Modifying Dictionary Data
update() - Add Multiple Items
Updates dictionary with multiple key-value pairs
person = {"name": "Alice"}
person.update({"age": 30, "city": "Boston"})
print(person) # {'name': 'Alice', 'age': 30, 'city': 'Boston'}
# Update with another dictionary
more_info = {"job": "Engineer", "hobby": "Reading"}
person.update(more_info)
print(person) # {'name': 'Alice', 'age': 30, 'city': 'Boston', 'job': 'Engineer', 'hobby': 'Reading'}
setdefault() - Add if Key Doesn't Exist
Sets a value only if the key doesn't already exist
settings = {"theme": "dark"}
# Add new key with default value
settings.setdefault("language", "English")
print(settings) # {'theme': 'dark', 'language': 'English'}
# Won't change existing key
settings.setdefault("theme", "light")
print(settings) # {'theme': 'dark', 'language': 'English'}
🔹 Removing Dictionary Data
pop() - Remove and Return Value
Removes a key and returns its value
inventory = {"apples": 10, "bananas": 5, "oranges": 8}
# Remove and get value
apple_count = inventory.pop("apples")
print(apple_count) # 10
print(inventory) # {'bananas': 5, 'oranges': 8}
# Pop with default value
grape_count = inventory.pop("grapes", 0)
print(grape_count) # 0
popitem() - Remove Last Item
Removes and returns the last key-value pair
scores = {"Alice": 95, "Bob": 87, "Charlie": 92}
last_item = scores.popitem()
print(last_item) # ('Charlie', 92)
print(scores) # {'Alice': 95, 'Bob': 87}
clear() - Remove All Items
Removes all items from the dictionary
data = {"a": 1, "b": 2, "c": 3}
data.clear()
print(data) # {}
🔹 Copying Dictionary Data
copy() - Make a Copy
Creates a shallow copy of the dictionary
original = {"name": "John", "age": 25}
backup = original.copy()
original["age"] = 26
print(original) # {'name': 'John', 'age': 26}
print(backup) # {'name': 'John', 'age': 25}
fromkeys() - Create from Keys
Creates a new dictionary with specified keys and same value
keys = ["name", "age", "city"]
empty_person = dict.fromkeys(keys, "Unknown")
print(empty_person) # {'name': 'Unknown', 'age': 'Unknown', 'city': 'Unknown'}
# With different default value
zero_scores = dict.fromkeys(["math", "science", "english"], 0)
print(zero_scores) # {'math': 0, 'science': 0, 'english': 0}