Say I have a dict d = {'a': 1, 'b': 2}
, and d.keys()
returns ['a', 'b']
, can I count on d.values()
to be [1, 2]
?
1 Answers
If you want both the keys and the values, you should use dict.items()
, which renders the question meaningless.
The answer is: Yes, they are usually in the same order, but no, you can't trust that. The reason is that keys()
will list the keys in the internal order (which depends on hash values). values()
will typically list the values by returning the value for each key, and the key again will be in the internal order. So yes, they will match. For Python built in dict class, they will match:
If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.
But that is an implementation detail, not of your platform, but of the mapping class. So if your mapping is anything else than the built in dict class, you can no longer be sure that this is the case. And with Pythons "duck typing" you shouldn't assume that you are using the dict class.
But as mentioned above the question is pointless, you never need to trust it.

- 167,292
- 41
- 224
- 251
-
2
-
1@Rob: Sometimes people ask the wrong question, and then they need to know the answer to the question they should have asked. :-) – Lennart Regebro Apr 03 '13 at 06:51
-
2
-
@Rob: No, but in this case, the question *is* meaningless, as you never need to know if the order is the same or not. – Lennart Regebro Apr 03 '13 at 06:54
-
2Python [reference for `dict.items()`](http://docs.python.org/2/library/stdtypes.html#dict.items) explicitly claims the opposite, the order remains the same unless the dict is modified. – bereal Apr 03 '13 at 06:56
-
-
Was writing that for some previous version of the answer... The behaviour is guaranteed for the standard dicts, but you're valid about the duck-typing issue. – bereal Apr 03 '13 at 07:02
-
Well, the previous version said the same thing, but sure, it wasn't as clear. – Lennart Regebro Apr 03 '13 at 08:17
-
if I try to compete the same objects it works ok. values = dict.values(); values.__eq__(values) -> True. So we can se that __eq__ is implemented in dict_values. Why it works in this way? – Ilya Miroshnichenko May 23 '19 at 13:13