Inverse of dict(zip(x,y))

Piet van Oostrum piet at cs.uu.nl
Wed Mar 4 07:57:01 EST 2009


>>>>> Andre Engels <andreengels at gmail.com> (AE) wrote:

>AE> On Wed, Mar 4, 2009 at 11:02 AM, lone_eagle <icymist at gmail.com> wrote:
>>> Can someone suggest a easy method to do the inverse of dict(zip(x,y))
>>> to get two lists x and y?
>>> 
>>> 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, ...]

>AE> x = d.keys()
>AE> y = [d[e] for d in x]

>AE> y = d.values() might also work, but I am not sure whether d.keys() and
>AE> d.values() are guaranteed to use the same order.

Yes, they are if the dictionary is not changed in the meantime (not even
inserting and removing the same thing). See the library documentation,
section dict.
-- 
Piet van Oostrum <piet at cs.uu.nl>
URL: http://pietvanoostrum.com [PGP 8DAE142BE17999C4]
Private email: piet at vanoostrum.org



More information about the Python-list mailing list