Locked learning resources

Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Locked learning resources

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

How to Modify Values in a Dictionary While Iterating Through It

00:00 Hi. In this video, we’re going to be going through the third on my list of this table of contents: how to modify values in a dictionary while iterating through it.

00:09 This is going to kind of expand our knowledge from just how to look at things in dictionaries to how to really do complex, powerful operations on dictionaries as you move through them.

00:19 Let’s move into the terminal, and I’m going to define a little dictionary here as an example for us. And the idea is just going to be that it’s going to be some fruits, and then some prices in cents, or fractions of a dollar. And, you know, you can imagine that if you were someone who had a store, you might want to keep track of your fruits and their prices in this way.

00:42 So here we have our example dictionary. Let’s rename that. Let’s call it prices = example, and now we’ll work with prices.

00:51 So, that’ll be a little simpler and a little easier to understand. Starting back up, prices. Great. Let’s imagine, for example, you have your store and the economy’s not doing so great, maybe, or maybe it’s doing really well and you can charge 10 more cents for each fruit. So, how would you do that? Well, you might start out this way, and you’d be totally correct.

01:11 You’d say for key in prices: and then prices at key equals what it already is,

01:18 prices[key], plus .1. So we’re increasing every price by 10 cents. And what does this do if we look at prices? Well, it works pretty much perfectly, aside from this odd little floating-point addition madness that sometimes happens in Python. This is due to how floating-point numbers are stored in Python.

01:38 Sometimes they can be a little bit finicky. But either way, it’s clear that what we’ve done is we’ve added 10 cents to each of our original prices. So this is great, and this is really the paradigm you should use when you want to modify values in a dictionary at any time.

01:53 You’re pretty much always going to have to use the key paradigm and then access the original dictionary at that key. Now, you might be thinking “Well, we learned all of these cool ways of going through dictionaries and looking at things in a kind of easier manner.” You know, we can assign names to the key and the value, and then we can print them out and do stuff with them. So you might say, “Well, why don’t I just do for key, value in prices.items(): value = value + .1.” Or let’s say + .2, just so it’s more obvious what happens.

02:24 But this doesn’t actually quite work the way that you might hope. Let’s take a look at what prices is. Oh, it’s exactly the same as the last time we looked at it. Well, that’s kind of weird, because we went through and we iterated through.

02:36 And clearly, if you go through and you say this, you say

02:41 print(key, value), then we get all of these items. So we clearly have access to them in some sense. But we can’t modify them in quite the same way. Well, why is this? Really, it comes back to this question about what is, actually, prices.items().

02:56 And if we look at it, it’s a dict_items object. And what this really means is it’s a specific object designed to show you what’s in a dictionary without actually giving you access to this dictionary.

03:09 And that’s really helpful when you’re designing large applications, because if you’re working with other programmers and other software packages, then you can give other people view access to what’s in the dictionary. They can look at your data, but they can’t modify it.

03:24 And you can imagine many different scenarios in which this might be really, really helpful for you as a developer. So, keep that in mind when you’re trying to modify the values of a dictionary.

03:32 You really need to access the original dictionary using a key. Otherwise, you won’t really be able to change things. You’ll just be able to look at them, maybe even copy them, but you won’t be able to change them.

03:43 So, our next step is how do you modify keys in a dictionary? Well, one very, very simple way if you just want to add one, is you can just say, you know, your a dictionary at a new key equals some value.

03:56 You just set it equal manually. And this works great, we’ve added 'kiwi'. It has a price of 1, they’re pretty expensive. But you have to do this manually, right?

04:06 And maybe you have a list you want to iterate through, and you can plug that in a list. But there are some circumstances where you might feel like what you want to do is say something like this, for key in prices: and then you might want to start adding and subtracting from the dictionary as you go along with different keys, right?

04:23 And I failed to mention that the way to remove a key is you use this this Python inbuilt del (delete) keyword. But let’s see what happens when we do this inside a loop.

04:34 Boom. We get a RuntimeError. And I think the best way to explain why exactly this happens is to think about it in an analogy with a real person or set of people, right? Imagine someone gave you a bucket of fruits and they said “I want you to put a sticker on every fruit in this bucket.” But then as you were doing that, going through these fruits, they started to throw more fruits in the bucket and take some of them out before you were able to put stickers on them. That doesn’t work, right?

05:01 It doesn’t make any sense. What does it even mean to say for key in prices when prices is constantly changing? So, this doesn’t work, and this is something that you should avoid doing when you’re working with loops in Python—adding and deleting keys as you loop through.

05:15 If you really need to do it, though, what you can do is you can say for key in list(prices.keys()):. So you can convert them to a list, and then you can say prices at, I don’t know—you can loop and simultaneously add and subtract from the dictionary however you want to do it. Right? So, let’s print out our prices.

05:42 And so we do have 'kiwi' at 2 and there are no errors. And realistically, of course, this isn’t something you’d actually want to do, because there’s no need to loop here.

05:51 But you might think of other more complex applications where a similar principle happens. However, one thing to keep in mind is that converting it to a list does use more memory, because this prices.keys(), it gets the keys one at a time from the dictionary, whereas converting it to a list makes you access all of these and put them in a data structure.

06:10 So if you’re doing this with a huge amount of data, it might not be ideal. So, we’ve gone over how to modify the values in a dictionary and how to modify the keys in a dictionary, and we’ve covered also some common pitfalls of ways that that might go wrong.

06:24 The key insight here is when you want to modify the values, you’re going to have to necessarily interact with the original dictionary. If you don’t, then you’re not going to actually get any results.

06:37 So we’d do something like this, and then we’d get prices, and they’ve all been changed to 1, right? And then if you want to modify keys in a dictionary, it’s always safest to just do this kind of semi-manually, right? Let’s see. prices at 'tomato', that’s a fruit, equals .2.

06:56 It’s always safer to modify the keys in this way than it is to try to do them in a loop. And if you do need to do them in a loop and you need to change the keys as you go along, then convert it to a list first.

07:08 So. That’s how to change and modify the keys and the values in a dictionary in iteration.

Avatar image for Kiran

Kiran on Dec. 29, 2019

Modify keys in the dictionary is nothing but adding new keys but not updating any existing key. is that right?

Avatar image for Liam Pulsifer

Liam Pulsifer RP Team on Dec. 30, 2019

@Kiran sure, I suppose that’s reasonable. I used “modify keys” to refer to adding or deleting keys because Python doesn’t offer an explicit operation (that I know of) to modify keys in a dictionary, other than deleting one and adding another.

Avatar image for mikesult

mikesult on May 5, 2020

It make sense that you can’t “modify” a key since it is immutable. So just delete the old and add a new one if you needed to change the key.

del prices['apple']
prices['granny_smith_apple'] = .5

Also it follows that trying to update ‘value’ doesn’t work because key and value are part of an immutable tuple. I’m kind of surprised it doesn’t throw an error.

for key, value in prices.items():
    value = value + 0.2
# no change in prices
Avatar image for Liam Pulsifer

Liam Pulsifer RP Team on May 6, 2020

@mikesult these are great intuitions you’re developing, especially regarding the dictionary keys. I want to quickly clarify something about your comment on value updating – the reason that trying to update value in the way you demonstrate does nothing productive but also doesn’t throw an error is because under the hood, it looks like this

for tuple in prices.items():
    key, value = tuple
    value = value + 0.2

So in reality, you’re not trying to modify the tuple. What you’re really modifying is simply a new variable value that has the same value as the corresponding element of the tuple. Of course, that has nothing to do with the real “value” that resides in the dictionary. If, on the other hand, you tried to do this

for tuple in prices.items():
    tuple[1] = tuple[1] + 0.2

you would get an error for trying to assign to a tuple. I hope these subtleties make sense!

Avatar image for mikesult

mikesult on May 6, 2020

Perfect explanation. Thanks.

Avatar image for yasserkgl

yasserkgl on May 25, 2020

hello I have the below error message

prices={'orange':'4', 'apple': 3, 'banana':7}
for key in prices:
    prices[key] = prices[key] + 1


Traceback (most recent call last):
  File "D:/Users/y.moneim/PycharmProjects/untitled2/Test002.py", line 62, in <module>
    prices[key] = prices[key] + 1
TypeError: can only concatenate str (not "int") to str
Avatar image for jaosunita

jaosunita on June 5, 2020

@yasserkgl, apostrophes in ‘4’ must be eliminated. Regards!

Avatar image for Liam Pulsifer

Liam Pulsifer RP Team on June 5, 2020

Good question @yasserkgl and good answer @jaosunita!

Avatar image for naomifos

naomifos on March 22, 2021

Hello I was wondering what you would do if you had, say a list of dictionaries and your function is looking for a specific key. How would you be able just to add the values of that certain key and return it? If that makes sense.

Avatar image for Bartosz Zaczyński

Bartosz Zaczyński RP Team on March 23, 2021

@naomifos Is this what you were asking about?

people = [
    {"name": "Joe", "age": 42},
    {"name": "Bob"},
    {"name": "Anna","age": 23}

total_age = 0
for person in people:
    if "age" in person:
        total_age += person["age"]
Avatar image for naomifos

naomifos on March 23, 2021

@Bartosz Zaczyński yes thank you so very much!

Become a Member to join the conversation.