Loops, and where your data lives

INPUT · Slides

Change it, add to it, take things out

01 / 07

Changing a value

Write the same shape you use to take something out, but on the left of an =, and you change that value.

It feels just like putting a value into a variable. You are dropping a new value into the slot called person["age"].

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

Result

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

02 / 07

Adding a new key

Surprisingly, adding is written exactly the same way.

  • if the key is already there … it is overwritten
  • if the key is not there … it is added

Not having to write the two cases apart is easy going, but it is also a trap: mistype a key and a different item quietly appears.

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

Result

{'name': 'Yui', 'hobby': 'reading'}

03 / 07

Building up from empty

Since you can add, you can start from {} and put keys in one at a time.

They line up in the order you added them, so put them in the order that reads best when you come back to it.

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

Result

{'name': 'bakery', 'price': 150}

04 / 07

Removing with del

A key you have finished with can be removed with del. You write del person["age"].

Look that key up afterwards and you get a KeyError, naturally. del on a key that is not there is a KeyError too, which makes you want to check whether it exists before removing it.

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

Result

{'name': 'Yui'}

05 / 07

Checking for a key with in

The plainest way to avoid a KeyError is to check before you look. You use in.

When you use in on a dictionary, what it looks at is the keys. It will not go hunting through the values, so keep that in mind.

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

Result

True
False

06 / 07

Deciding what happens when it is missing, with get

The other way is get. Write person.get("hobby", "unset") and, when the key is missing, you get back the second thing you handed it.

Leave the second one out and you get None. Either way, nothing stops with an error — that is what get is for.

person = {"name": "Yui"}print(person.get("hobby", "unset"))print(person.get("name", "unset"))print(person.get("hobby"))

Result

unset
Yui
None

07 / 07

Choosing between in and get

Pick between the two tools by what you are trying to do.

  • if "hobby" in person: … do something only when it is there
  • person.get("hobby", "unset") … use this instead when it is not

Both are there to head off a KeyError. Reach straight for person["hobby"] only when you are certain the key exists.

Next we take the contents out one at a time and loop over them.

person = {"name": "Yui"}if "hobby" in person:    print(person["hobby"])else:    print("no hobby on file")

Result

no hobby on file