Inverse of dict(zip(x,y))

Peter Otten __peter__ at web.de
Wed Mar 4 05:27:42 EST 2009


Andreas Tawn 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, ...]
>>
>>Cheers,
>>Chaitanya.
> 
> x = d.keys()
> y = d.values()

But be aware that you lose order and of course duplicate keys:

>>> d = dict(zip("abca", "xyzt"))
>>> d.keys()
['a', 'c', 'b']
>>> d.values()
['t', 'z', 'y']

See also the note for the dict.items() method at
http://docs.python.org/library/stdtypes.html#mapping-types-dict

Peter



More information about the Python-list mailing list