Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Corresponding Dictionary Keys and Values Outputs [duplicate]

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?

like image 874
Clodoaldo Neto Avatar asked Nov 19 '25 03:11

Clodoaldo Neto


1 Answers

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

like image 71
Jean-François Fabre Avatar answered Nov 20 '25 17:11

Jean-François Fabre



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!