Order of elements in a dict

Leif K-Brooks eurleif at ecritters.biz
Tue Apr 26 05:46:00 EDT 2005


Marcio Rosa da Silva wrote:

> So, my question is: if I use keys() and values() it will give me the 
> keys and values in the same order?

It should work fine with the current implementation of dictionaries, but 
(AFAIK) it's not guaranteed to work by the mapping protocol. So 
theoretically, it could break under Python 2.5 or with a user-made 
mapping type.

> Also, if someone has a better way to exchange keys and values in a dict, 
> I would like to learn. :-)

I would do it like this:

 >>> d = {1: 2, 2: 3, 3: 4}
 >>> d = dict([(value, key) for key, value in d.iteritems()])
 >>> d
{2: 1, 3: 2, 4: 3}



More information about the Python-list mailing list