Inverse of dict(zip(x,y))

Paul Rubin http
Wed Mar 4 05:06:34 EST 2009


lone_eagle <icymist at gmail.com> writes:
> So, if x and y are two lists, it is easier to make a dictionary using
> d = dict(zip(x,y)), but if I have d of the form, d = {x1:y1,
> x2:y2, ...}, what is there any trick to get lists x = [x1, x2, ...]
> and y = [y1, y2, ...]

This may be a bit of a mind bender, but:

  x, y = zip(*d.items())

The trick is that if xys is a list of pairs, then zip(*xys) splits
out the pairs, e.g.:

     >>> zip(*((1,2),(3,4),(5,6)))
     [(1, 3, 5), (2, 4, 6)]

I found that in the python docs somewhere.  The mind wobbles.



More information about the Python-list mailing list