Real-World Tasks With Dictionary Iteration
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.
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.
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.
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
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
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.
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.
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: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.
Become a Member to join the conversation.