Dictionaries
Programming Languages · Python Functions & Data · 12 min
Store values under names (keys), look them up, change them and count with them.
Keys and values
A dictionary stores pairs: a key and its value, like a word and its meaning. Use curly brackets, and a colon between key and value:
user = {"name": "Bo", "level": 5}
print(user["name"]) # Bo
You look things up by key, not by position.
Create a dictionary
petwith"name"set to"Rex"and"age"set to3.Print the pet's name by looking up the
"name"key.
Adding and changing
Put a value under a key with =. If the key exists, its value is replaced. If not, a new pair is added.
user = {"level": 5}
user["level"] = 6 # change
user["team"] = "blue" # add
Change the
"age"ofpetto4.Add a new key
"sound"with the value"woof".
Is the key there?
Looking up a key that doesn't exist crashes your program. Two safe ways to check first:
user = {"name": "Bo"}
print("name" in user) # True
print(user.get("team", "none")) # none
.get(key, backup) gives the value, or the backup if the key is missing.
Print whether
"sound"isinthepetdictionary.Print
pet.get("sound", "none").
Looping over a dictionary
.items() gives you every key and value, one pair at a time. Use two loop variables to catch them:
ages = {"Ada": 36, "Bo": 9}
for name, age in ages.items():
print(name, age)
Loop over
prices.items()and print lines likeapple costs 2.
Counting with a dictionary
Dictionaries are great at counting. For each thing, add 1 to its count. .get(thing, 0) starts new things at 0:
counts = {}
for letter in "abba":
counts[letter] = counts.get(letter, 0) + 1
print(counts) # {'a': 2, 'b': 2}
Loop over
fruitsand add 1 to each fruit's count incounts.After the loop, print
counts.
Put it together: a gradebook
Keep a class's grades in a dictionary. Add a new student, fix a mistake, print everyone's grade and work out the average.
Add
"Di"with grade88, and change"Bo"to82.Loop over
grades.items(), print lines likeAda: 91, and add each grade tototal.After the loop, print
Average: 86.5, usingtotal / len(grades).