d.keys() and d.values()

Oren Tirosh oren-py-d at hishome.net
Tue Jun 24 14:09:41 CEST 2003


On Tue, Jun 24, 2003 at 12:03:33PM +0200, Gerrit Holl wrote:
> Hi,
> 
> is it guaranteed that dict(zip(d.keys(), d.values())) == d?
> In words, do .keys() and .values() always have the same order? Is
> it safe to rely on this?

Yes, as long as the dictionary is not modified between these calls.

http://www.python.org/doc/current/lib/typesmapping.html
"""
(3)
  Keys and values are listed in random order. 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()]".
"""

	Oren





More information about the Python-list mailing list