Marcio Rosa da Silva wrote:
Hi!

In dictionaries, unlinke lists, it doesn't matter the order one inserts the contents, elements are stored using its own rules.

Ex:

 >>> d = {3: 4, 1: 2}
 >>> d
{1: 2, 3: 4}

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

In other words, it is safe to do:

 >>> dd = dict(zip(d.values(),d.keys()))

to exchange keys and values on a dictionary? Or I can have the values and keys in a different order and end with something like this:

 >>> dd
{2: 3 , 4: 1}

instead of:

 >>> dd
{2: 1, 4: 3}

For this example it works as I wanted (the second output), but can I trust this?

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

Thanks!

Marcio

Well, a footnote to the "Mapping types" page in the Library Reference says

"""Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary's history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond. This allows the creation of (value, key) pairs using zip(): "pairs = zip(a.values(), a.keys())". The same relationship holds for the iterkeys() and itervalues() methods: "pairs = zip(a.itervalues(), a.iterkeys())" provides the same value for pairs. Another way to create the same list is "pairs = [(v, k) for (k, v) in a.iteritems()]". """

So it looks as though you will be safe, since there's a promise in the documentation.

If you just want to iterate over the (key, value) pairs, however, you should normally choose items() or iteritems() to do so. Then you could use (for example):

dd = dict((x[1], x[0]) for x in d.items())

I presume you are confident that each value will only occur once in the original dictionary, as otherwise the result will be smaller than the input.

regards
 Steve
--
Steve Holden        +1 703 861 4237  +1 800 494 3119
Holden Web LLC             http://www.holdenweb.com/
Python Web Programming  http://pydish.holdenweb.com/

--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to