How to Use itertools With Dictionaries
All right! So, I’m going to be talking in this video about
itertools is really an amazing Python library which allows you to just do an incredible number of iterative tasks on any kind of iterable collection.
And so it prevents you from having to…Say you want to go through this list, you know, 10 times and do a certain set of things each time. Well, you don’t want to write 10
for loops. That would just be silly.
This isn’t anything that you would actually do in a real application, of course. So, there we go. As you can see, we’re iterating through in order and over and over until we reach our stop condition, which in this case was just that there are 10 items in the total number of iterations, right? So that’s how you use
cycle(). And of course, if I hadn’t included this breakout condition, we would just keep cycling forever, but that would be boring to watch so I didn’t want to do that.
Another cool thing from
itertools is the
chain() function. And so, what’s fun about that, if you remember from
ChainMap—which we did in the last video—this is a very similar idea, except it doesn’t create an object which has these chained properties.
It just allows you to iterate through a chained version of the things. So for example, let’s define a dictionary called
fruits, which is just going to go
'apple' goes to
'banana' goes to
it’s just going to be
5 carrots, and then we’ll have a bunch of potatoes—
45. So, we have
veggies. If you remember for a
ChainMap, we would have defined a
ChainMap with these
veggies, and then we would have iterated through it. But instead what you can do is you can say
for item in chain(fruits.items(), veggies.items()):
you can just, you know, print the
item. And you can do all sorts of things with it, but we’re just going to print it. So as you can see, we’ve chained up these two dictionaries and allowed us to iterate through all of the items in both of them without having to use any unwieldy
for loop constructions. We just looped through this chained thing.
You can also use
.values(), whatever else you want to do—anything that’s iterable. You could even chain together the two dictionaries themselves, but then it would be
for key in the chain of the two dictionaries.
itertools gives us just some new options for iterating through dictionaries and their items. It’s pretty fun, and I would encourage you to check out the documentation of
itertools for more on what it can do, ‘cause it’s a really amazing library. Thanks!
Become a Member to join the conversation.