Dictionaries
A dictionary stores key-value pairs. Instead of looking items up by position, you look them up by a key, the way you look up a word in a real dictionary.
Python
student = {
"name": "Asha",
"age": 21,
"city": "Mumbai",
}
print(student["name"])
print(student["age"])Keys are usually strings, but any immutable value works (numbers, tuples). Each key appears only once.
Adding and changing
Assigning to a key adds it, or replaces its value if it already exists:
Python
student = {"name": "Asha", "age": 21}
student["email"] = "asha@example.com" # add
student["age"] = 22 # change
print(student)Removing
Python
stock = {"apples": 10, "pears": 4, "kiwis": 0}
del stock["kiwis"]
pears = stock.pop("pears") # remove and return the value
print(pears, stock)Missing keys
Looking up a key that doesn't exist raises a KeyError:
Python
prices = {"tea": 20, "coffee": 35}
print(prices["juice"])Use in to check first, or get(), which returns None (or a default you choose) instead of crashing:
Python
prices = {"tea": 20, "coffee": 35}
print("juice" in prices)
print(prices.get("juice"))
print(prices.get("juice", "not on the menu"))
print(prices.get("tea", 0))Counting with a dictionary
A classic use: counting how often things appear.
Python
text = "the cat and the hat and the bat"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)counts.get(word, 0) + 1 means "the current count, or 0 if new, plus one".
Dictionaries keep insertion order
Since Python 3.7, dictionaries remember the order in which keys were added.
Python
d = {}
d["z"] = 1
d["a"] = 2
d["m"] = 3
print(d)
print(len(d))Building a dictionary
Python
names = ["Asha", "Leo", "Mei"]
scores = [92, 78, 85]
results = dict(zip(names, scores))
print(results)
squares = {n: n * n for n in range(1, 6)} # a dictionary comprehension
print(squares)Finished this lesson?Mark it complete to earn +20 XP and move your progress on.