Loops, and where your data lives

INPUT · Slides

A container you look up by name

01 / 06

A number tells you nothing

A list let you hold values in a row. But look at ["Yui", 15] — can you tell what the 15 is a count of?

Age? A score? A height? With a container you index by number, remembering what the contents mean becomes your job.

person = ["Yui", 15]print(person[0])print(person[1])

Result

Yui
15

02 / 06

Hold it under a name

That is what a dictionary is for. Inside {} you list pairs of name: value, separated by commas.

To take something out you put the name in the brackets instead of a number. Write person["name"] and it is clear at a glance what you are pulling out.

person = {"name": "Yui", "age": 15}print(person["name"])print(person["age"])

Result

Yui
15

03 / 06

Keys and values

Two words to learn.

  • key … the name you use to take something out. The "name" part
  • value … what is stored there. The "Yui" part

A key and a value always go in together. Look a value up by its key — that is the whole of a dictionary.

shop = {"name": "bakery", "price": 150}print(shop["price"])

Result

150

04 / 06

Showing the whole thing

print a dictionary as it is and everything comes out. It comes out in the order you wrote it.

The text arrives wrapped in ' though. You wrote ", so why? That is simply how Python shows you what it is holding, and nothing about the contents has changed. You can leave it be for now.

person = {"name": "Yui", "age": 15}print(person)

Result

{'name': 'Yui', 'age': 15}

05 / 06

Ask for a key that is not there and it errors

Ask a dictionary for a key it does not have and Python stops with a KeyError.

It is the same as pointing past the end of a list: it tells you plainly that there is nothing there. It will not quietly hand you None instead.

person = {"name": "Yui"}print(person["hobby"])

Result

KeyError: 'hobby'

06 / 06

A value can be anything

A value can be text, a number, True or None. Nothing has to match anything else, which is part of what makes a dictionary easy to live with.

A dictionary holding nothing at all is written {}. Starting empty and adding keys as you go is the next lesson.

shop = {"name": "bakery", "price": 150, "open": True}print(shop["open"])print({})

Result

True
{}