d.keys() and d.values()
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:
> 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.
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()]".
More information about the Python-list