A dictionary maps keys to values. Keys must be hashable and unique; values can be anything.
student = {
"name": "Ada",
"score": 95,
"passed": True,
}Curly braces surround the dictionary. Each entry is key: value, and entries are separated by commas.
Accessing values#
student = {"name": "Ada", "score": 95}
print(student["name"]) # Ada
print(student["score"]) # 95Accessing a missing key raises KeyError. Use get() when absence is expected:
print(student.get("email")) # None
print(student.get("email", "unknown")) # unknownThe second argument is the default returned when the key is missing. The default expression is evaluated before get() is called, so avoid expensive work there unless it is necessary.
Adding and updating#
student = {"name": "Ada"}
student["score"] = 95
student["score"] = 97
student.update({"passed": True, "level": 2})
print(student){'name': 'Ada', 'score': 97, 'passed': True, 'level': 2}
Assigning to an existing key replaces its value. update() merges another dictionary or an iterable of pairs.
Removing entries#
student = {"name": "Ada", "score": 95}
score = student.pop("score") # remove and return
del student["name"] # remove by key
student.clear() # remove everythingpop() accepts a default for missing keys: student.pop("email", None). del raises KeyError when the key is absent.
Checking keys#
student = {"name": "Ada"}
print("name" in student) # True
print("email" in student) # False
print(len(student)) # 1Membership tests keys, not values. To test a value, use "Ada" in student.values().
Iterating#
scores = {"Ada": 90, "Grace": 95, "Linus": 88}
for name in scores:
print(name)
for score in scores.values():
print(score)
for name, score in scores.items():
print(f"{name}: {score}")Iteration order is insertion order. Sorting keys explicitly makes output deterministic:
for name in sorted(scores):
print(name, scores[name])Counting with a dictionary#
A very common pattern accumulates counts:
words = ["apple", "banana", "apple", "cherry", "apple"]
counts = {}
for word in words:
counts[word] = counts.get(word, 0) + 1
print(counts){'apple': 3, 'banana': 1, 'cherry': 1}
get() supplies 0 for a new word, so the addition always works.
Dictionary comprehensions#
numbers = [1, 2, 3, 4]
squares = {number: number ** 2 for number in numbers}
print(squares)
lengths = {word: len(word) for word in ["one", "three", "seven"]}
print(lengths)A comprehension is readable when the key and value are simple expressions.
Nested data#
users = {
"ada": {"score": 95, "active": True},
"grace": {"score": 88, "active": False},
}
for username, profile in users.items():
status = "active" if profile["active"] else "inactive"
print(f"{username}: {profile['score']} ({status})")Nested dictionaries are common in JSON data. Access one level at a time and check for missing keys when the structure is not guaranteed.
Practice#
Read a sentence, split it into words, and count each word with a dictionary. Print the words in alphabetical order with their counts. Then print only the words that appear more than once.
