Week 7: Expanding Your Data Structure Toolkit
Explore tuples and dictionaries to organize data in powerful ways.
Explore Chapter 7Common Dictionary Methods.
Dictionaries provide several useful methods for working with their data.
- `keys()`: Returns a view object that contains all the keys in the dictionary.
ages = {"Alice": 30, "Bob": 25, "Charlie": 40} all_keys = ages.keys() # Returns a view object, not a list in Python 3 - `values()`: Returns a view object that contains all the values in the
dictionary.
all_values = ages.values() # Returns a view object - `items()`: Returns a view object that contains all the key-value pairs in the
dictionary as tuples.
all_items = ages.items() # Returns a view object of (key, value) tuples - `get(key, default)`: Returns the value associated with the `key`. If the `key`
is not found, it returns the `default` value (or `None` if no `default` is provided). This is a
safer way to access values than using `[]` as it avoids `KeyError`s.
alice_age = ages.get("Alice") # 30 david_age = ages.get("David", "Not found") # "Not found" - `pop(key, default)`: Removes the key and returns the corresponding value. If
the key is not found, it returns the `default` value (or raises a `KeyError` if no `default` is
provided).
removed_age = ages.pop("Bob") # 25 # ages.pop("David") # Raises KeyError if "David" is not a key ages.pop("David", "Not found") # Returns "Not found" if "David" is not a key - `popitem()`: Removes and returns an arbitrary (key, value) pair. (The
last-inserted item is removed in versions before Python 3.7).
last_item = ages.popitem() - `clear()`: Removes all items from the dictionary.
ages.clear() # ages is now {} - `copy()`: Returns a shallow copy of the dictionary.
ages_copy = ages.copy() - `update(other_dict)`: Updates the dictionary with the key-value pairs from
`other_dict`. Existing keys are overwritten, and new keys are added.
more_ages = {"Eve": 28, "Frank": 33} ages.update(more_ages)