A dict maps keys to values. Keys are unique. Lookup is by key, not by position.
Goal
Set, get, iterate, and nest a small dict of people.
Build and read
person = {"name": "Ada", "city": "Nairobi", "score": 98}
print(person["name"])
print(person.get("team", "none"))
print("city" in person)
print(list(person.keys()))
print(list(person.values()))Missing person["team"] raises KeyError. .get returns the default instead.
Set and delete
person = {"name": "Ada", "score": 91}
person["score"] = 98
person["city"] = "Nairobi"
del person["score"]
print(person)Iterate
scores = {"Ada": 98, "Alan": 91, "Grace": 95}
for name, score in scores.items():
print(f"{name}: {score}")
print(sum(scores.values()))Nested
team = {
"Ada": {"city": "Nairobi", "score": 98},
"Alan": {"city": "Mombasa", "score": 91},
}
print(team["Ada"]["city"])
print(team["Alan"]["score"])Pitfall
{} is an empty dict, not an empty set. Empty set is set().