Order of elements in a dict

Duncan Booth duncan.booth at invalid.invalid
Tue Apr 26 05:31:28 EDT 2005


Marcio Rosa da Silva wrote:

> In other words, it is safe to do:
> 
> >>> dd = dict(zip(d.values(),d.keys()))
> 
> to exchange keys and values on a dictionary?

See the Library Reference, section 2.3.8 Mapping Types:

> 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()]". 





More information about the Python-list mailing list