livepython.net
CHAPTER 13Dictionaries
13.3  CHANGE ITEMS

Add, Update and Delete Dictionary Items in Python

Add a New Key or Change a Value

To add an item to a dictionary, assign a value to a new key: ages["Lucky"] = 22. The very same line changes the value when the key already exists.

Think of it like a whiteboard of names and scores: writing a new name adds a line, and writing on an existing name rubs out the old score and puts in the new one.

PYTHONedit me
ages = {"Sunny": 25, "Rocky": 30}
ages["Lucky"] = 22
print(ages)
ages["Sunny"] = 26
print(ages)
OUTPUT
{'Sunny': 25, 'Rocky': 30, 'Lucky': 22}
{'Sunny': 26, 'Rocky': 30, 'Lucky': 22}

The rules

  • d[key] = value with a new key adds a pair at the end.
  • d[key] = value with a key that's already there replaces its value. The key keeps its place.
  • A dictionary is changed in place, like a list with append() in chapter 9. No new dictionary is made.

Add up with +=

+= from chapter 5 works on a value too. Here, 5 more apples arrive at the shop:

PYTHONedit me
stock = {"apple": 10, "mango": 4}
stock["apple"] += 5
print(stock)
OUTPUT
{'apple': 15, 'mango': 4}

Avoid: += on a key that isn't there

+= first reads the old value. If there is no old value, Python stops:

PYTHONedit me
stock = {"apple": 10}
stock["kiwi"] += 5
print(stock)
OUTPUT
KeyError: 'kiwi'

To add a brand-new key, use =, not +=: stock["kiwi"] = 5. Or use get() with a default from the last topic, which works either way: stock["kiwi"] = stock.get("kiwi", 0) + 5.

Common beginner doubt: "How do I rename a key?" There's no rename. Add the new key with the old value, then delete the old key. You'll learn deleting two lessons from now.

d[key] = value adds the key if it's new and changes its value if it's already there.

your turnPredict the output

What will this print?

pet = {"name": "Rocky", "age": 3} pet["age"] = 4 pet["color"] = "brown" print(len(pet))
Your turn! What will this code show on the screen?
your turnSpot the bug

Which line breaks?

One line stops this program. Tap it.

Update a Dictionary with update()

The update() method adds the pairs of one dictionary to another in one go. Keys that are new get added; keys that already exist get the new value.

Think of it like updating your contacts from a friend's list: new names are added, and if a name is already there, its number is replaced with the newer one.

PYTHONedit me
prices = {"apple": 40, "mango": 60}
prices.update({"mango": 70, "kiwi": 25})
print(prices)
OUTPUT
{'apple': 40, 'mango': 70, 'kiwi': 25}

Mango already existed, so its price changed from 60 to 70. Kiwi was new, so it was added at the end.

The rules

  • d.update(other) puts every pair of other into d.
  • New keys are added at the end; existing keys keep their place and get the new value.
  • other doesn't change.
  • update() changes d in place and gives back None, just like sort() on a list in chapter 9.

One call or several lines

These two do the same thing:

PYTHONedit me
profile = {"name": "Sunny"}
profile.update({"age": 25, "city": "Pune"})
print(profile)

same = {"name": "Sunny"}
same["age"] = 25
same["city"] = "Pune"
print(same)
OUTPUT
{'name': 'Sunny', 'age': 25, 'city': 'Pune'}
{'name': 'Sunny', 'age': 25, 'city': 'Pune'}

For one or two keys, d[key] = value is easiest to read. When you already have a second dictionary, like new prices from a supplier, update() is the shortcut.

Avoid: storing what update() gives back

PYTHONedit me
prices = {"apple": 40}
prices = prices.update({"kiwi": 25})
print(prices)
OUTPUT
None

update() gives back None, and that line stores it in prices, so the whole dictionary is lost! Call it on its own line, without prices =.

d.update(other) adds the new keys and replaces the values of the old ones, in place.

your turnFill the gap

Add Lucky's mark and change Rocky's

marks = {"Sunny": 80, "Rocky": 65} marks.?({"Rocky": 70, "Lucky": 90}) print(marks)

It should print: {'Sunny': 80, 'Rocky': 70, 'Lucky': 90}

Which piece makes this code work?
your turnType the output

Type what this prints

a = {"x": 1, "y": 2} a.update({"y": 5}) print(a["y"] + a["x"])
Read the code line by line, then type the output exactly.

Remove Dictionary Items with pop() and del

To remove an item from a dictionary, use pop(key) or del d[key]. Both take out the key together with its value. pop() also gives you the value it removed.

Think of it like taking a coat back from the coat check: with pop() you hand in the ticket and get the coat back in your hands. With del, the coat is simply thrown away.

pop(): remove and keep the value

PYTHONedit me
cart = {"apple": 3, "bread": 1, "milk": 2}
gone = cart.pop("bread")
print("Removed", gone, "bread")
print(cart)
OUTPUT
Removed 1 bread
{'apple': 3, 'milk': 2}

You've met pop() on lists in chapter 9. On a dictionary, you give it a key, not an index.

del: remove and forget

PYTHONedit me
cart = {"apple": 3, "bread": 1, "milk": 2}
del cart["apple"]
print(cart)
OUTPUT
{'bread': 1, 'milk': 2}

A missing key

Both stop with a KeyError when the key isn't there:

PYTHONedit me
cart = {"apple": 3}
cart.pop("cake")
OUTPUT
KeyError: 'cake'

pop() has a safe version, like get(): give it a default, and it gives that back instead of an error.

PYTHONedit me
cart = {"apple": 3}
print(cart.pop("cake", 0))
print(cart)
OUTPUT
0
{'apple': 3}

The rules

You writeRemovesGives backMissing key
d.pop(key)that pairthe valueKeyError
d.pop(key, default)that pairthe value, or the defaultthe default
del d[key]that pairnothingKeyError
d.clear()every pairnothingan empty {}

Common beginner doubt: "Should I use pop() or del?" Use pop() when you need the value you're removing, like the quantity of the item you take out of the cart. Use del when you don't. Or check with in first, then del.

pop(key) removes a pair and gives back its value; del d[key] only removes it.

your turnPredict the output

What will this print?

stock = {"pen": 4, "ink": 2} n = stock.pop("pen") print(n, len(stock))
Your turn! What will this code show on the screen?
your turnFix the code

Remove Rocky only if he is in the dictionary

It should print: {'Sunny': 10, 'Lucky': 7}

team = {"Sunny": 10, "Lucky": 7}
del team["Rocky"]
print(team)
This code does not work yet. Fix it, then press Run.

Build a Dictionary from Input

You can build a dictionary step by step: start with an empty {}, then add one pair in every round of a loop. It's the same pattern you used to build a list with append() in chapter 10.

Think of it like a teacher filling in a register: the page starts empty, and each student adds one line with their name and mark.

PYTHONedit me
marks = {}
for i in range(3):
    name = input()
    mark = int(input())
    marks[name] = mark
print(marks)
OUTPUT
{'Sunny': 82, 'Rocky': 67, 'Lucky': 91}

Each round reads two lines, a name and a mark, and adds them as one pair.

The pattern

StepCodeWhere
start emptymarks = {}before the loop
add one pairmarks[name] = markinside the loop
use the resultprint(marks)after the loop

How many pairs?

Often the first line of input says how many pairs follow, just like the questions in chapter 10:

PYTHONedit me
count = int(input())
prices = {}
for i in range(count):
    item = input()
    prices[item] = int(input())
print(len(prices), "items:", prices)
OUTPUT
2 items: {'tea': 15, 'coffee': 25}

Avoid: making the dictionary inside the loop

If prices = {} sits inside the loop, every round starts a new, empty dictionary, and only the last pair survives:

PYTHONedit me
for i in range(2):
    prices = {}
    item = input()
    prices[item] = int(input())
print(prices)
OUTPUT
{'coffee': 25}

No error, but tea is gone. Make the empty dictionary before the loop.

Common beginner doubt: "What if the same name is typed twice?" Then the second mark replaces the first, because keys are unique. That's often exactly what you want, like a newer price replacing an old one.

Start with {} before the loop, add d[key] = value inside it, use the dictionary after it.

your turnOrder the lines

Put the lines in order to store two names and marks, then print them.

  1. for i in range(2):
  2. print(marks)
  3. marks = {}
  4. marks[name] = int(input())
  5. name = input()

The user types: Sunny82Rocky67

These lines are mixed up. Put them back in order, then press Check.
your turnPredict the output

What will this print?

n = 3 while n > 0: print(n) n -= 1
Your turn! What will this code show on the screen?

Practice: Change items

Solve these to lock in what you learned in this topic. Each one runs in your browser.

  1. 114.Python Program to Add or Update a Mark in a DictionaryEasySolve
  2. 115.Python Program to Remove an Item from a Shopping CartMediumSolve
  3. 116.Python Program to Build a Price List from InputMediumSolve