How to Update and Add Keys in a Python Dictionary

Read the old value to make the new one — and setting a NEW key creates it on the spot.

  • Lesson 2 of 5
  • PRO
  • Ages 10+
  • 3 hands-on levels
See what PRO unlocksA one-time $49.99 purchase. Topics 1–3 are free.

The dragon explains

Updating a stat, adding a new one

  1. The dragon: Just like a variable, a dict's value can change. Same pattern you already know.

  2. The dragon: dragon["hp"] = dragon["hp"] - 15 reads the CURRENT hp, subtracts 15, and stores that back under "hp".

    example.pyPython 3
    dragon = {"hp": 40}dragon["hp"] = dragon["hp"] - 15print(dragon["hp"])
    Output25
  3. The dragon: You can also add a key that never existed before, just by setting it: dragon["element"] = "fire" creates a brand new key.

    example.pyPython 3
    dragon["element"] = "fire"print(dragon["element"])
    Outputfire
  4. The dragon: A dict grows by naming a new key — no special command needed, unlike a list's append().

Quick check

Check your understanding

Say your answer out loud before reading the marked one. Every wrong option is a mistake real beginners make.

  1. Question 1 of 2

    dragon = {"hp": 40}. What does dragon["hp"] = dragon["hp"] - 15 do?

    question.pyPython 3
    dragon = {"hp": 40}dragon["hp"] = dragon["hp"] - 15
    • It reads the current hp (40), subtracts 15, and stores 25 back under the hp keyCorrect
    • It stores the TEXT "dragon[\"hp\"] - 15" under the hp key

    Why: It reads 40, subtracts 15, and stores 25 back under "hp" — the same "compute first, store the result" rule as any variable update.

  2. Question 2 of 2

    dragon = {"name": "Ember"} has no "element" key. What happens if you write dragon["element"] = "fire"?

    • It creates a brand new key called "element" with the value "fire"Correct
    • It causes an error, since "element" doesn't exist yet

    Why: It creates the "element" key on the spot, with the value "fire". A dict grows just by naming a new key and giving it a value.

In the game

What you'll practice

Three levels in the game: one guided first try with the shape of the answer already there, then two to solve on your own.

  1. 1

    GuidedYour first try

    dragon = {"name": "Ember", "hp": 40}. Print the hp, then set dragon["hp"] to dragon["hp"] minus 15 (damage taken), then print hp again — showing the change.

  2. +2

    PracticeTwo more, on your own

This lesson is part of PRO.

PRO is a one-time $49.99 purchase, no subscription, and unlocks this whole topic along with everything else. Topics 1–3 are free, start to finish.

Unlock this lesson with PRO

Stuck three times? The game offers the answer — unasked.