3

As a dictionary is not ordered the output is also not ordered:

>>> d = dict(b = 1, a = 2, z = 3)
>>> d.keys()
['a', 'z', 'b']
>>> d.values()
[2, 3, 1]

But are the keys and values outputs above always in corresponding order?

Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260
  • 1
    Note, (pedantic point) dictionaries are ordered in CPython 3.6 http://stackoverflow.com/questions/39980323/dictionaries-are-ordered-in-cpython-3-6 – Chris_Rands Jan 27 '17 at 11:01
  • @Chris_Rands I read that and it looks like it is not clear if that should be relied upon. – Clodoaldo Neto Jan 27 '17 at 11:14
  • @ayhan The text and sample here are clearer than in the other question. – Clodoaldo Neto Jan 27 '17 at 11:48
  • I don't agree. The title itself explains the issue. If you think it would improve with a clearer example you can always edit it but I don't think it is a good enough reason to close that canonical question as a duplicate of this one. – ayhan Jan 27 '17 at 12:05
  • @ayhan It is not necessary to be one and not the other. It can be both. – Clodoaldo Neto Jan 27 '17 at 12:38

1 Answers1

7

The answer is yes.

From python 2 documentation:

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(d.values(), d.keys()). The same relationship holds for the iterkeys() and itervalues() methods: pairs = zip(d.itervalues(), d.iterkeys()) provides the same value for pairs. Another way to create the same list is pairs = [(v, k) for (k, v) in d.iteritems()].

And from python 3 documentation

If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219