Dictionaries and dict.get()
Look values up by key. get() returns a default instead of an error when the key is missing.
Syntax
stats = {"hp": 20}stats["hp"]stats.get("battery", 0)
- Assigning to a new key adds it.
Example
stats = {"hp": 20}
print(stats["hp"])
print(stats.get("battery", 0))Output:
20 0
Common mistakes
- stats["missing"] raises a KeyError. Use get() when the key may be absent.