Sub topic 1
Creating dictionaries
Prerequisites
This chapter assumes basic Python syntax, variables, functions, f-strings, for loops, conditionals, and the str, int, list, and tuple types. You should also know that mutable objects can change after creation, while immutable objects cannot.
A dictionary (dict) maps each key to a value. Keys identify entries and must be hashable, meaning Python can compute a stable hash for them. Strings, numbers, and tuples containing only hashable values can be keys. Lists and dictionaries cannot, because they are mutable.
prices = {"apple": 0.50, "pear": 0.75}
also_prices = dict(apple=0.50, pear=0.75)
from_pairs = dict([("apple", 0.50), ("pear", 0.75)])
print(prices == also_prices == from_pairs) # True
lengths = {word: len(word) for word in ["cat", "house"]}
print(lengths) # {'cat': 3, 'house': 5}What can be a key: hashability
A tuple can be a key when every item inside it is hashable. A tuple containing a list is not valid as a key.
locations = {(51.5, -0.1): "London"}
print(locations[(51.5, -0.1)])
try:
locations[[51.5, -0.1]] = "Invalid"
except TypeError as error:
print(error) # unhashable type: 'list'Reading values: `[]`, `get()` and `in`
Indexing with data[key] returns the value, but raises KeyError if the key is absent. Use get() when a missing key is expected. The in operator tests key membership.
user = {"name": "Ada", "role": "admin"}
print(user["name"])
print(user.get("email", "not provided"))
print("role" in user)Adding, updating and removing entries
Assignment adds a new entry or replaces an existing value. update() changes several entries. pop() removes and returns one value, while del removes an entry without returning it.
stock = {"apple": 3}
stock["pear"] = 5
stock["apple"] += 2
stock.update({"banana": 4, "pear": 6})
removed = stock.pop("banana")
stock.pop("kiwi", None)
del stock["apple"]
print(removed) # 4
print(stock) # {'pear': 6}Exercise
Write one statement that adds "theme": "dark" to settings, then safely reads "font" with "default" when it is absent.
Show answer
settings["theme"] = "dark"; font = settings.get("font", "default")