Lesson explanation
After this lesson, you will be able to:
A dictionary maps keys to values. It is useful for named settings and records, where settings["region"] is clearer than remembering a numeric position. A literal uses {key: value} entries; an empty dictionary is {}. Keys must be hashable (strings are a common choice), and each key is unique: assigning the same key again replaces its value.
Read a known value using record[key], and assign record[key] = new_value to add or update it. Looking up a missing key with square brackets raises KeyError.
Check key membership with key in record before reading an optional field. This checks whether a key exists, not whether its value is truthy: a stored 0, False, "", or None may still be valid data. Use del record[key] to remove an existing key; check membership first when it may be absent.
Square brackets look up the value belonging to a key.
account = {"team": "payments", "retries": 3}
print(account["team"])
print(account["retries"])Output:
payments
3Assigning a missing key adds it; assigning an existing key changes its value.
config = {"region": "us", "retries": 2}
config["region"] = "eu"
config["enabled"] = True
print(config["region"])
print(config["enabled"])Output:
eu
TrueMembership tests the key's presence, not the stored value.
profile = {"user": "Maya", "attempts": 0}
print("attempts" in profile)
print("active" in profile)Output:
True
FalseDeleting removes the entry completely.
settings = {"debug": False, "port": 8000}
del settings["debug"]
print(len(settings))
print("debug" in settings)Output:
1
False| Need | Python |
|---|---|
| Create mapping | {"region": "eu"} |
| Read a known key | config["region"] |
| Add or update | config["enabled"] = True |
| Check a key exists | "enabled" in config |
| Delete an existing entry | del config["enabled"] |
| Count entries | len(config) |
record["missing"] raises KeyError when the key does not exist.key in record checks keys, not values.0 is still a value for a present key..get() and its default behavior are introduced in the next lesson; use key-membership checks here.