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

Applications

00:00 In this lesson, I’m going to continue taking you through the applications for the zip() function out in the Python world. The ones in this lesson are going to include building dictionaries using zip(), sorting multiple iterables at once, and a couple of others.

00:16 The first thing that I want to show you is how to build a basic dictionary from a list of keys and a list of values—or really, any iterable of keys and iterable of values.

00:27 So, the pattern for that will look like you just declare whatever new dictionary you want, and then you can declare it as dict(zip(keys, values)).

00:37 And this works in a really easy fashion because the dictionary constructor dict() can just take in a list or an iterable of tuples where each tuple has a key and a value. And that’s exactly what zipping together a keys iterable and a values iterable does for you.

00:54 Let’s take a look at it in the Python REPL.

00:57 I’ve whipped up a couple of lists—one of keys and one of the values. The keys are our programming languages and values are the kind of general framework that they fall under, so Python is object-oriented, as is C++, whereas C is more of a procedural language.

01:12 And so if you want to have a dictionary mapping each language to its type, then you can simply say d = dict(zip(keys, values)). Really, really simple, and it works perfectly as long as the corresponding key and value are at the same index, which they should be if you are getting ready to use zip() on them, at all times.

01:33 So, there’s more things that you can do with this kind of paradigm as well, because you can pass in any iterable to the keys and the values here. So, say you modify values so values[2] = "Blah"and of course, Blah isn’t a kind of programming language, but just for the sake of example.

01:52 You could remap this dictionary, but you could actually pass in the dictionary itself as the first iterable that you pass to zip() because the default iterable—or, the default iterator for a dictionary iterates over its keys.

02:06 So you can actually use this dict(zip()) paradigm with a dictionary itself if you want to remap the keys. So, that’s something that’s interesting in a different way to kind of look at this paradigm, is you can really pass in any iterables that you want to this zip() function, as long as it generates a list or an iterator of tuples with a key and a value in each tuple.

02:27 Another cool thing you can do is you can sort multiple iterables with precedence based on one of those iterables. So what I mean by that is if you have several different iterables, like animal_names, animal_weights, and animal_lengths, and you have one particular way that you want to combine these in sorted order, then what you can do is you can zip all of them together and then sort it, and the sorted() order will be based on the first iterable that you pass into the zip() function.

02:58 And the reason for that is because when Python sorts an iterator of tuples—as is what’s going to happen if you sort this zip() output—tuples are always sorted based on their first index first, then their next index if there’s a tie, then their final index.

03:13 So it goes in order of indexing into the tuple, so if you pass it in this first thing as animal_names, animal_names is what it will sort by.

03:20 So, let’s show you how that works in the REPL.

03:24 Here are the same lists that I just had in the slide example. If I just take a look at the exact same example that I just showed—so animal_names, and then animal_weights, and then animal_lengths

03:43 then you can see that the first tuple in the output is ('anaconda', 550, 28) So, it still has all of the correct mappings, right? 'anaconda' is still paired up with 550 and 28the other things at the second index—but that actually comes first in the output because of the sorted() ordering that you pass in when you pass in animal_names first.

04:06 And then the next tuple is 'hippo', of course, but it’s the 'hippo' that has the smaller weight, because that’s the next object in here. But if I pass them in in different orders, then you’ll get different outputs here, actually. So, animal_weights, animal_lengths, and then animal_names.

04:28 And so in this case I get each tuple is ordered differently, but the actual tuples that come out happened to be—in this case—in exactly the same order, which is really interesting. So what if I do now—what if I zip by—oh, and this will just be faster just to type it again. So sorted(zip(animal_lengths, animal_names,—and thenanimal_weights)).

04:53 So as you can see, the animal with the shortest length—which is the 'hippo' that has length 12 and weight 5000, so the shorter but heavier 'hippo'—that comes first because the animal_length is the first parameter. And the 'anaconda' has by far the biggest length, so it’s in the back.

05:10 But now if I could do one more thing and I could say sorted() with reverse=True,

05:16 and then that will give you the exact reverse order. So, there’s a lot of ways to play with this and to get the exact order that you want from an iterator of tuples that’s created by the zip() function, just based on what you pass into it. In previous lessons, I showed you how to do some basic calculations on parallel iterables, but when you combine this kind of framework with list comprehensions and dictionary comprehensions, then you can get some really powerful stuff using just a zip() function combined with one of those comprehensions.

05:49 Let’s take a look over in the REPL to see how that can work.

05:53 Let’s say you run a used car dealership and you have separate data storage for the income that you make off of any particular sale, the cost that it was to you to purchase the car—which you then sold later—and then the actual car makes that you’re selling.

06:09 If you want to use list comprehensions and the zip() function to create some nice readable output, your first thought might be to say something like profits = [income - cost for income, cost in zip(incomes, costs)].

06:25 And notice how this is actually kind of putting together everything that I have done in this series so far, right? Because I’m using this nice way to assign readable names using zip(), I’m iterating through, and I’m generating output based on it. And that output then you can wrap up in a list comprehension to make a really nice readable way to generate this data. And so these data are the profits, so income minus cost for each of these different cars, right?

06:53 And if you want to make things a little bit more complex, you might want to start creating something like a profit_map where you map—in a dictionary data structure—each item to its profit, right?

07:04 So, {item: income - cost for item, income, cost in zip(items, incomes, costs)}. And remember that when you do something like this, you have to make sure that this item, income, cost is in the same order as the iterables that each of these is coming from. But this part—so, the part before the for—doesn’t actually matter what order they’re in, right? So I could have said income maps to item, or something like that, and it could be out of order and it wouldn’t be a big deal.

07:33 But everything in this side of the actual equation needs to be in the same order. So, taking a look at profit_map, as you can see, it maps the three different items to the profits that you’d made off of them, right?

07:45 And you can make this stuff arbitrarily complex in the dictionary comprehension, right? Maybe you want to go a little bit more in-depth and you want to get the ratio of the profit to the original cost that you paid for it, right?

08:00 That’s totally possible. And as you can see, it maps 'Ford' to 4.0, 'Chevy' to 3.0, and 'Chrysler' to 0.2777—whatever.

08:07 And so you know that the 'Ford' has the best profit-to-cost ratio, and that might be something that you’re interested in if you’re selling these kind of used cars. So you can do whatever, you can put whatever you want in here.

08:18 Just be wary that sometimes the dictionary or list comprehension will start to get incredibly long, in which case you might want to start to package this stuff into a function, right?

08:28 Which you can then just call the function on these three inputs without having to worry about it getting super, super long. So, that’s how you use list and dictionary comprehensions, along with the calculations that you can do from zip(), to generate really nice and readable output from zipped input.

08:46 These are really just a few of the unlimited number of cool things that you can do with the zip() function. So I encourage you, now that you have a nice fundamental understanding of how this works, to just play around with applying this zip() paradigm to a bunch of different things in Python.

09:02 I think that one of the joys of really understanding something well—as I’m sure you do after watching this series—is to just have the chance to be creative with it and just see what kind of new permutations and new expressions that you can find for this particular function, and then anything else that you learn in the language.

Become a Member to join the conversation.