Python Basics — Accessing & Modifying Dictionaries
Accessing & Modifying Dictionaries
Learn how to read, add, update, and delete dictionary entries.
Bracket Notation
user = {"name": "Alice", "age": 30, "city": "New York"}
print(user["name"]) # Alice
print(user["age"]) # 30
If the key doesn’t exist, you get a KeyError:
# print(user["email"]) # KeyError: 'email'
.get() — Safe Access
user = {"name": "Alice", "age": 30}
print(user.get("name")) # Alice
print(user.get("email")) # None (no error!)
print(user.get("email", "N/A")) # N/A (custom default)
Rule of thumb: Use
[]when you’re sure the key exists. Use.get()when a key might be missing.
Adding Key-Value Pairs
user = {"name": "Alice"}
user["age"] = 30
user["email"] = "alice@example.com"
print(user)
# {'name': 'Alice', 'age': 30, 'email': 'alice@example.com'}
Updating Existing Values
user = {"name": "Alice", "age": 30}
user["age"] = 31 # update existing key
print(user) # {'name': 'Alice', 'age': 31}
Deleting Entries
del Statement
user = {"name": "Alice", "age": 30, "city": "New York"}
del user["city"]
print(user) # {'name': 'Alice', 'age': 30}
# KeyError if key doesn't exist
# del user["phone"] # KeyError: 'phone'
.pop() — Delete and Return Value
user = {"name": "Alice", "age": 30, "city": "New York"}
city = user.pop("city")
print(city) # New York
print(user) # {'name': 'Alice', 'age': 30}
# With default (no error if missing)
phone = user.pop("phone", "N/A")
print(phone) # N/A
.popitem() — Remove Last Inserted
user = {"name": "Alice", "age": 30, "city": "New York"}
last = user.popitem()
print(last) # ('city', 'New York')
print(user) # {'name': 'Alice', 'age': 30}
.setdefault() — Get or Set
Returns the value if the key exists. If not, inserts the key with the given default:
user = {"name": "Alice"}
# Key exists — returns existing value
name = user.setdefault("name", "Unknown")
print(name) # Alice
# Key doesn't exist — inserts and returns default
age = user.setdefault("age", 0)
print(age) # 0
print(user) # {'name': 'Alice', 'age': 0}
Practical Use — Grouping
words = ["apple", "banana", "avocado", "blueberry", "cherry"]
grouped = {}
for word in words:
first_letter = word[0]
grouped.setdefault(first_letter, []).append(word)
print(grouped)
# {'a': ['apple', 'avocado'], 'b': ['banana', 'blueberry'], 'c': ['cherry']}
KeyError Handling
user = {"name": "Alice"}
# Option 1: Check first
if "email" in user:
print(user["email"])
else:
print("No email")
# Option 2: get() with default
print(user.get("email", "No email"))
# Option 3: try/except
try:
print(user["email"])
except KeyError:
print("No email")
Checking Key Existence
user = {"name": "Alice", "age": 30}
print("name" in user) # True
print("email" in user) # False
print("email" not in user) # True
inchecks keys, not values.
Summary
d["key"]— access (raisesKeyErrorif missing)d.get("key", default)— safe accessd["key"] = value— add or updatedel d["key"]— delete (raisesKeyErrorif missing)d.pop("key", default)— delete and returnd.popitem()— delete and return last paird.setdefault("key", default)— get or insert"key" in d— check if key exists
Next up: Dictionary Methods →