Calmcode - comprehensions: zip

Zip

1 2 3 4 5 6 7 8 9

You can "repackage" data in python by using zip. Dictionaries have an .items() method that offers a lot of freedom.

d = {'a': 1, 'b': 2, 'c': 3}
[(k, v) for k, v in d.items()]

Using .items() you can have access to both the keys and the values. You could use it, for example, to quickly double all the values in a dictionary;

d = {'a':1, 'b':2}
{k: v * 2 for k, v in d.items()}

Another function to be aware of is zip. It allows you to "zip" lists together like a zipper.

[(a, b) for a, b in zip([1, 2, 3], [4, 5, 6])]

You can also zip three arrays together.

[(a, b, c) for a, b, c in zip([1, 2, 3], [4, 5, 6], [7, 8, 9])]