Real-World Tasks With Dictionary Iteration
00:00 Okay, welcome! Today we’re going to be covering some real-world tasks with dictionary iteration, some things that you might actually want to do if you were working with dictionaries.
00:10 An important note before we start is that this is going to be a first video where we go through some of these tasks and how you can implement them. In the next video, number 5, we’re going to talk about some advanced ways to do this, which are the really Pythonic, beautiful ways to do these same tasks.
00:27 But what I think is important is that in this video we go through and you see what’s happening under the hood so that you’re really clear on the concepts.
00:33
And then in the next one we’ll talk about how to do them in a really clean and easy way. So, let’s go over to the terminal. I’ve got my a_dict
.
00:41 It has mappings of the string forms of the first four numbers to their actual numeric forms. And let’s imagine that we want to turn those keys into values and vice versa.
00:54
One way to do this is to create a new dictionary and then simply loop through the keys and the values in the .items()
representation of this dictionary.
01:06
And then we can just add to this new dictionary the kind of inverse of each key-value pair in a_dict
. So, let’s take a look at new_dict
. Oh, I’m sorry—do you see what I did wrong? Take a quick second and ask yourself “What did he do here that messed things up?” It’s very, very simple.
01:26
I just put a colon (:
) instead of an equals (=
). So. We all do stuff like this on occasion. Let’s take a look now at new_dict
. And as you can see, we’ve accomplished our goal here to turn our keys into values and vice versa.
01:41 So, that’s one kind of thing you might want to do in Python. The next thing you might want to do is you might want to filter your items. You might want to only include items which satisfy some criteria.
01:52
Let’s look at a_dict
again. And let’s just go back up here. I’m sorry to delete that, you can feel free to rewind if you want to look back again at that more closely.
02:02
So, we have a_dict
, and let’s say we want to just include the items in a new dictionary for which the values are greater than 2
.
02:12
One way to do that, again, in this kind of iterative paradigm is to say for key in a_dict:
02:21
we want to add to new_dict
only if the value of—and let’s do this in the .items()
representation again. I told you that was going to be very convenient. So if the—and we don’t want to call it values
, it’s only one value
.
02:38
So, if value > 2
, then we want to say new_dict[key] = value
. Right? So, this is really spelling this out in a very brute force way.
02:51
And we can see we just have those key-value pairs for which the value is greater than 2
. So, another example of something that you might want to do is you might want to do some quick calculations on each item in your dictionary. And so, for example, let’s make a dictionary called incomes
, and it’s going to just have a few names. We’re going to have 'jeff'
.
03:20
Man, it’s so hard to think of names on the spot. I don’t know why it is, but it is. Let’s say 'annie'
, and she’s going to make a little more than Jeff. And then we’ve got…
03:33
'glen'
, and Glen makes a lot of money. And so there we have our incomes
dictionary and it’s all well and good. And then maybe we just want to know the total income.
03:46
So we could say total_income = 0
. Then we can say for income in incomes:
03:59
I’m sorry, uh, for key, income in incomes.items()
. That’s how I wanted to go about this. So with the .items()
paradigm it’s really easy to iterate through and do things with the data. But as I said, it’s more difficult to modify, so that’s something that you’ll want to keep in mind.
04:19
So, I said incomes
instead of income
—classic story, and now we’ve got the total_income
right here. So be careful with these little bugs when you’re naming things in a dictionary iteration, because this is very easy to do.
04:32
You can say for key, income in incomes.items()
, and then you can accidentally use incomes
instead of income
. So you might want to think about being more clever about naming your variables than I just was, because if they’re too similar to one another, that’s always an issue.
04:46
So, that was an example of some basic calculations that you can do with dictionaries and with the keys and the values using this .items()
paradigm.
04:54 In the next video, we’re going to talk about some advanced techniques using dictionary comprehensions, which will accomplish the same things that we just did in much more concise and elegant style.
yasserkgl on May 26, 2020
Hellow
i follow the same example as you have explained but the output with some error
#inverse key with value
dic5={'red':7 ,"blue":8,"black":9 , "orange":22}
for key ,value in dic5.items():
dic5[value]=key
print(dic5)
output
Traceback (most recent call last): File “D:/Users/y.moneim/PycharmProjects/untitled2/Test002.py”, line 68, in <module> for key ,value in dic5.items(): RuntimeError: dictionary changed size during iteration
joshengroff on Aug. 22, 2020
You put print(prices)
inside your for
loop which prints out the updated dictionary the number of times it was iterated over (3).
Try it like this:
prices={'orange':4, 'apple': 3, 'banana':7}
for key in prices:
prices[key] = prices[key] + 2
print(prices)
Liam Pulsifer RP Team on Aug. 23, 2020
Well said @joshengroff, and sorry to miss your comments @yasserkgl. The reason you’re seeing the error you mentioned above is because you’re iterating through your dictionary while changing it – this makes the Python runtime unsure of what items to include in the iteration. When you swap the keys and values in a dictionary, it’s normally much easier to make a new dictionary with the swapped items, like so:
d = {'a': 5, 'b': 6, 'c': 7}
swapped_d = {value: key for key, value in d.items()}
Become a Member to join the conversation.
yasserkgl on May 26, 2020
hello
I tried to test thed same as you have explained but i find the below
output
Why it is repeated 3 times?