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 pet with "name" set to "Rex" and "age" set to 3.

  • 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" of pet to 4.

  • 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" is in the pet dictionary.

  • 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 like apple 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 fruits and add 1 to each fruit's count in counts.

  • 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 grade 88, and change "Bo" to 82.

  • Loop over grades.items(), print lines like Ada: 91, and add each grade to total.

  • After the loop, print Average: 86.5, using total / len(grades).

More in Python Functions & Data

Previous: Functions · Next: Classes