Python's Not (Just) For Unicorns

An interactive introduction to programming in Python, for human beings and whoever else

Chapter 22

Intro to dictionaries

In the last chapter, we struggled with finding a way to store a lot of information about a single person. We tried two ways:

# Separate named variables for separate pieces of info
name = "Annie"
age = 83
town = "Cleveland"

# One variable for each person, with a list
annie = ["Annie", 83, "Cleveland"]
  • Separate variables were good for remembering that name was her name and age was her age
  • Separate variables were bad because we had to keep track of three variables for one person
  • A list was good because it allowed us to store one person’s information in one variable
  • A list was bad because it was hard to remember whether her name was stored in annie[0] or annie[1] - the numbers aren’t easy to understand like name or age were.

If we could combine the two approaches our lives would be a lot easier. What we seem to need is one variable with multiple named things inside. And hey, Python can do that!

annie = {'name': 'Annie', 'age': 83, 'town': 'Cleveland'}

print(annie['name'], "is", annie['age'], "and is from", annie['town'])

Hooray! Life is perfect now. Our friend Annie has one variable named annie that has information about her, organized by topic.

This data type is called a dictionary. Dictionaries are a single variable, but they can have all sorts of labeled information inside. If we have a dictionary variable named annie, name can be stored as annie['name'] and an age can be stored as annie['age'], instead of using [0] and [1] like we had to do with lists.

Dictionaries might look a little like lists, but they have a few major differences:

Dictionary List
Created using { and } [ and ]
Inside Punctuation Has commas Has commas
Names? Yes No (numbers instead)
Creation {'name': 'Annie', 'age': 83} ['Annie', 'Roberto']
Getting data annie['name'] friends[0]

If we think creating a dictionary on one line looked a little messy, we can also use multiple lines. Just pay attention to the commas!

# You can make a dictionary all on one line...
roberto = { 'name': 'Roberto', 'age': 103, 'town': 'Reno' }

# ...or you can do it on multiple lines.
roberto = {
  'name': 'Roberto',
  'age': 103,
  'town': 'Reno'

print(roberto['name'], 'is', roberto['age'], 'and is from', roberto['town'])

Python dictionaries are pretty similar to a real dictionaries - if have a dictionary named roberto and want to look up his name, I open up to the 'name' page. If I want to learn about his age, I find the definition under 'age'. With Python, it just becomes roberto['name'] and roberto['age']

For no reason whatsoever, let’s talk about a house! Create a dictionary below named house with the following information in it.

key value
address 99 Main Street
price 50000
year 1980

  • Hint: Use curly braces - { and } - to wrap the dictionary
  • Hint: If we’re creating it across multiple lines, make sure to put a comma , at the end of (almost) every line (see roberto up above)
  • Hint: Their next-door neighbor might be at house = { 'address': '101 Main Street', 'price': 45000, 'year': 1989 }

Cool, ’eh? Now let’s practice taking information out of dictionaries. This is a part we’ll probably mess up here and there, so we’re going to mess it up on purpose first so we can recognize the error when we see it.

It’s important to use strings when asking for information from dictionaries. Run the code below and read the error that happens if we use roberto[name] instead of roberto['name'].

roberto = {
  'name': "Roberto",
  'age': 103,
  'town': "Reno"

Pay attention to that error message, we’re certain to see it again! Now change the print line to use 'name' instead of name and see if the code works.

Notice how the color changes when you change it into a string? This doens’t mean working vs. not working, it just means name is a variable and 'name' is a string. We’ll talk more about the difference later!

Now that we’re on a dictionary roll: let’s try another one. It’s nice and long: create a dictionary named musician, and then print out Earl Scruggs played banjo using the new dictionary.

key value
name Earl Scruggs
instrument banjo
birth 1924
city Flint Hill, North Carolina
genre bluegrass

  • Hint: Use curly braces - { and } - to wrap the dictionary
  • Hint: If we’re creating it across multiple lines, make sure to put a comma , at the end of each line (see roberto up above)
  • Hint: Surrounding the entire city with quotes, like "Flint Hill, North Carolina" - don’t let that comma escape!
  • Hint: Use print with commas to print multiple things out
  • Hint: You can use print(musician['name'], "played", musician['instrument'])

We’ve been using dictionaries to hold multiple pieces of information about the same thing, but we can also use them for the same piece of information about multiple things1.

population = {
  'Santiago': 7.2,
  'San Diego': 1.407,
  'Nara': 1.401,
  'Moscow': 12.19
print("The population of Moscow is", population['Moscow'])

This technique is a lot more convenient than a list, because:

  • You get to store everything in one variable, and
  • You get to name each of your data points

We’ll only use it when we need to name each separate datapoint, though. If we just have a bunch of numbers without names a list will work just fine.

The one difference between Python dictionaries and real-life dictionaries is you can’t have duplicates in a Python dictionary. Only one definition for Moscow! Only one definition for Nara! But we’ll be okay.

Mini mission: New York City is made up of five boroughs. I’ve stored the population of each in a dictionary below. Print out the total population of New York City.

pop = {
  'Brooklyn': 2.637,
  'Staten Island': 0.474,
  'Manhattan': 1.645,
  'Queens': 2.339,
  'Bronx': 1.455
  • Hint: If we had separate variables like pop_bk and pop_si and pop_mn, you could add them like pop_bk + pop_si + pop_mn
  • Hint: We can’t do pop['Brooklyn' + 'Manhattan'], because the strings get combined first. It would be like typing pop['BrooklynManhattan']
  • Hint: Use each separately, pop['Brooklyn'], pop['Manhattan'], pop['Bronx'], etc.
  • Hint: pop['Brooklyn'] + pop['Staten Island'] + pop['Manhattan'] + pop['Queens'] + pop['Bronx']
  • Hint: Remember to use print to display the answer!

Chapter summary

We learned about dictionaries, which are ways of storing multiple (named) pieces of information in one variable. Once we get good at them, we’ve learned 100% of the Important Elements Of Programming!