0

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]?

satoru
  • 31,822
  • 31
  • 91
  • 141

1 Answers1

2

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.

Lennart Regebro
  • 167,292
  • 41
  • 224
  • 251