7.2. Core Operations#
Common dictionary operations involve the following methods.
Group |
Method |
Description |
|---|---|---|
Reading |
|
Return the value or a fallback without inserting |
|
All keys |
|
|
All values |
|
|
All key-value pairs |
|
Adding/Updating |
|
Add or overwrite from another dict |
|
Set value only if key doesn’t exist |
|
Removing |
|
Remove & return a specific key |
|
Remove & return last inserted pair |
|
|
Remove everything |
|
Copying/Creating |
|
Shallow copy |
|
Create new dict from a list of keys |
|
Checking |
|
Check if key exists |
|
Count of key-value pairs |
Lists identify elements by their positions; dictionaries identify values by their keys. The following table compares the core operations for both types.
Operation |
List |
Dictionary |
|---|---|---|
Read one value |
|
|
Read with a fallback |
No equivalent to dictionary |
|
Replace one value |
|
|
Add an item |
|
|
Delete without returning a value |
|
|
Remove by value |
|
No |
Remove and return one value |
|
|
Remove the last item |
|
|
Remove everything |
|
|
Test membership |
|
|
Iterate |
|
|
Count items |
|
|
For an invalid lookup or removal without a fallback, a list raises IndexError for an out-of-range index, while a dictionary raises KeyError for a missing key.
7.2.1. Accessing Items#
Use d[key] to retrieve the value associated with a key. If the key is absent, a regular dictionary raises KeyError. Whether that is a problem depends on the data contract: which fields must be present, and which may be absent.
Required field: use
d[key]when missing data should reveal an error that needs attention.Optional field: use
d.get(key, default)when absence is expected and the fallback has a meaningful interpretation.Create on first use: use
setdefault()when a missing entry should be inserted before you work with it.
A fallback is a design choice. Replacing a missing required grade with zero could produce a misleading average; reporting a missing optional phone number as "N/A" can be appropriate.
person = {
"name": "Alice",
"age": 28,
"city": "Rolla"
}
# Access an item
print(person["name"]) # Alice
print(person)
Alice
{'name': 'Alice', 'age': 28, 'city': 'Rolla'}
KeyError when trying to access a nonexistent key.
%%expect KeyError
print(person["phone"]) # KeyError
KeyError: 'phone'
get() returns a fallback only when the key is absent. With no explicit fallback, it returns None. It does not insert the fallback into the dictionary, and it does not replace an existing value, even when that value is None.
print(person.get("phone")) # None
print(person.get("phone", "N/A")) # N/A
None
N/A
7.2.1.1. Choose What Absence Means#
Compare these operations using the same missing key. The printed dictionary after each operation shows whether the lookup changes the data. setdefault() returns the existing value when the key is already present; it does not overwrite it.
record = {'name': 'Ana'}
print('Before:', record)
try:
print(record['phone']) # Required lookup: intentionally demonstrate KeyError.
except KeyError:
print('Required phone is missing')
print('After brackets:', record)
print('Optional phone:', record.get('phone', 'N/A'))
print('After get:', record)
print('Created phone:', record.setdefault('phone', 'N/A'))
print('After setdefault:', record)
print('Existing phone:', record.setdefault('phone', 'unknown'))
Before: {'name': 'Ana'}
Required phone is missing
After brackets: {'name': 'Ana'}
Optional phone: N/A
After get: {'name': 'Ana'}
Created phone: N/A
After setdefault: {'name': 'Ana', 'phone': 'N/A'}
Existing phone: N/A
In Section 7.3, defaultdict(list) extends the create-on-first-use pattern for grouping: bracket access creates a missing list, but .get() does not invoke the factory. Use it when creating groups is intended, rather than merely checking whether a group exists.
numbers = {'zero': 0, 'one': 1, 'two': 2}
To access all the keys and values at once:
keys()returns a view of all the dictionary’s keysvalues()returns a view of all the dictionary’s values.items()returns a view of all key-value pairs as tuples.
for k in numbers.keys():
print(k, end=' ')
print()
for v in numbers.values():
print(v, end=' ')
print()
for k, v in numbers.items():
print(k, v , end=' ')
zero one two
0 1 2
zero 0 one 1 two 2
The len function works on dictionaries; it returns the number of items.
len(numbers)
3
### Exercise: Accessing Dictionary Values
# Given the dictionary below:
# 1. Print the value associated with "name".
# 2. Use .get() to retrieve "email" with a default of "N/A".
# 3. Print all keys and values using .items().
person = {"name": "Bob", "age": 25, "city": "Chicago"}
### Your code starts here.
### Your code ends here.
Bob
N/A
name Bob
age 25
city Chicago
7.2.2. Adding/Updating Items#
You also use the square brackets to update values. An item assignment like person["age"] = 30 will either
updates an existing item, or
creates a new item if the key does not already exist.
Dictionary keys must remain hashable, with stable hashes and equality behavior while stored. Assigning to person["age"] changes the associated value, not the key.
# Modify an existing item
person["age"] = 29
# Add a new item
person["email"] = "alice@rolla.com"
print(person)
{'name': 'Bob', 'age': 29, 'city': 'Chicago', 'email': 'alice@rolla.com'}
d.update() is used to add new key-value pairs or change existing ones in a dictionary. d.update() behaves like above but can work with multiple key-value pairs:
if the key already exists, its value is replaced
if the key does not exist, it is added
d = {"a": 1, "b": 2}
d.update({"b": 20, "c": 3})
print(d) # {'a': 1, 'b': 20, 'c': 3}
{'a': 1, 'b': 20, 'c': 3}
An alternative syntax for d.update() is as follows.
d.update(a=10, d=4)
print(d) # {'a': 10, 'b': 20, 'c': 3, 'd': 4}
{'a': 10, 'b': 20, 'c': 3, 'd': 4}
To rename a dictionary entry, replace its key rather than changing the existing key object. You can:
Add a new key
Copy the value
Delete the old key
The following assignment uses pop() to remove the old entry and return its value, then stores that value under the new key.
student = {
"name": "Doris",
"age": 29
}
# Rename key "age" to "years"
student["years"] = student.pop("age")
print(student)
{'name': 'Doris', 'years': 29}
### Exercise: Adding and Updating Dictionary Items
# Start with this dictionary:
# 1. Add a new key "email" with value "alice@example.com".
# 2. Update "age" to 30.
# 3. Use d.update() to add "city": "Boston" and change "name" to "Alicia".
# 4. Print the final dictionary.
person = {"name": "Alice", "age": 28}
### Your code starts here.
### Your code ends here.
{'name': 'Alicia', 'age': 30, 'email': 'alice@example.com', 'city': 'Boston'}
7.2.3. Deleting Items#
You can remove a key-value pair when you no longer need it:
del d[key]removes the item with the given key.d.pop(key)removes the item with the given key and returns its value.d.popitem()removes the last inserted item and returns it as a(key, value)tuple.d.clear()removes all items.
del is a Python keyword used in a statement, rather than a method call. It deletes the target you specify: del d[key] removes a dictionary entry, del nums[0] removes a list element, and del nums[1:3] removes a list slice. You can also use del name to remove a variable binding; this does not necessarily destroy the object, because other variables may still refer to it. Unlike pop(), del does not return the removed value.
Both del d[key] and d.pop(key) raise KeyError if the key is missing. To handle a missing key without an error, use d.pop(key, default). It returns the default value and leaves the dictionary unchanged; it does not insert the default.
Unlike dictionary pop(), which requires a key, list pop(index) takes an optional index and has no default-value argument. List pop() with no argument is closer to dictionary popitem(): both remove the last item, but the list returns an element and the dictionary returns a key-value pair.
person = {
"name": "Alice",
"age": 29,
"city": "Rolla",
"email": "alice@rolla.com"
}
print("person:\t\t", person)
# Delete an item using del
del person["city"] # in place
print("city deleted:\t", person)
# Delete an item using pop()
email_popped = person.pop("email")
print("x_city_email:\t", person) # {'name': 'Alice', 'age': 29}
print("email_popped:\t", email_popped) # alice@rolla.com
print("person_updated\t", person)
# Delete the last added item using popitem()
key, value = person.popitem()
print("popped_k_v:\t", (key, value)) # ('age', 29)
print("after_popitem:\t", person) # {'name': 'Alice'}
# Clear all items from the dictionary
person.clear()
print("after_clear:\t", person) # {}
person: {'name': 'Alice', 'age': 29, 'city': 'Rolla', 'email': 'alice@rolla.com'}
city deleted: {'name': 'Alice', 'age': 29, 'email': 'alice@rolla.com'}
x_city_email: {'name': 'Alice', 'age': 29}
email_popped: alice@rolla.com
person_updated {'name': 'Alice', 'age': 29}
popped_k_v: ('age', 29)
after_popitem: {'name': 'Alice'}
after_clear: {}
person = {"name": "Alice", "city": "Rolla"}
print(person.pop("city", "N/A")) # Rolla: the key exists
print(person.pop("phone", "N/A")) # N/A: the key is missing
print(person) # {'name': 'Alice'}
Rolla
N/A
{'name': 'Alice'}
### Exercise: Deleting Dictionary Items
# Start with this dictionary:
# 1. Delete "city" using del.
# 2. Remove and capture "email" using pop(). Print the popped value.
# 3. Print the remaining dictionary.
person = {"name": "Bob", "age": 25, "city": "Boston", "email": "bob@email.com"}
### Your code starts here.
### Your code ends here.
Popped email: bob@email.com
{'name': 'Bob', 'age': 25}
7.2.4. Membership Testing#
The in membership operator works on dictionaries, too; it tells you whether a key exists in the dictionary, which returns True if the key is present and False if it is not. You can also use not in to check that a key is missing.
Member testing is useful when you want to safely decide whether to access, update, or delete a dictionary item.
person = {
"name": "Alice",
"age": 29,
"city": "Rolla"
}
print("name" in person) # True
print("email" in person) # False
print("email" not in person) # True
if "age" in person: # safety: Check if key exists before accessing
print("Age exists:", person["age"])
True
False
True
Age exists: 29
The in operator does not check whether something appears as a value.
"Alice" in person
False
To see whether something appears as a value in a dictionary, you can use the method values, which returns a sequence of values, and then use the in operator.
"Alice" in person.values()
True
### Exercise: Membership Testing
# Use the dictionary below:
# 1. Check if "name" is in the dictionary and print the result.
# 2. Check if "phone" is NOT in the dictionary and print the result.
# 3. Check if "Alice" appears as a value and print the result.
person = {"name": "Alice", "age": 29, "city": "Rolla"}
### Your code starts here.
### Your code ends here.
True
True
True