Skip to the content

Changing

Python · Unit 7: Dictionaries

To add a pair, assign to a new key: d[key] = value. If the key already exists, the same line changes its value.

That's why a dictionary never has two equal keys.

stock = {"bun": 4}
stock["milk"] = 2
stock["bun"] = 10
print(stock)

Prints

{'bun': 10, 'milk': 2}

The rest of the explanation is in the lesson, which is part of the full plan.

Exercises in this lesson

You do them in the app, which checks them on the spot and explains why.

  1. 1. Predict the output

    What does this code print?

  2. 2. Find the bug

    This program should add Jake with an 8 and show all the grades. Which line has the bug?

  3. 3. Complete the code

    Rice went up. Complete it so it costs 5 more than before.

  4. 4. Predict the output

    What does this code print?

  5. 5. Multiple choice

    What's the difference between del d["bun"] and d.pop("bun")?

  6. 6. Predict the output

    What does this code print?

  7. 7. Complete the code

    Complete it to remove the bun only if it's in the cart.

  8. 8. Put the lines in order

    Put in order the function that adds an item to the cart. If it was already there, it gets one more; if not, it goes in with 1.

  9. 9. Find the case that fails

    remove(cart, item) should take the item out and return the cart. If the item isn't there, it returns the cart unchanged. Which call does it fail with?

  10. 10. Predict the output

    This is how you count votes. What does it print?

Do this lesson

It opens in your browser. This lesson is part of the full plan; the first unit of each course is free.

See all lessons →