8

Possible Duplicate:
Python dictionary: are keys() and values() always the same order?

If i have a dictonary in python, will .keys and .values return the corresponding elements in the same order?

E.g.

foo = {'foobar' : 1, 'foobar2' : 4, 'kittty' : 34743}

For the keys it returns:

>>> foo.keys()
['foobar2', 'foobar', 'kittty']

Now will foo.values() return the elements always in the same order as their corresponding keys?

Community
  • 1
  • 1
UberJumper
  • 20,245
  • 19
  • 69
  • 87

3 Answers3

18

It's hard to improve on the Python documentation:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. 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()]

So, in short, "yes" with the caveat that you must not modify the dictionary in between your call to keys() and your call to values().

David Citron
  • 43,219
  • 21
  • 62
  • 72
1

Yes, they will

Just see the doc at Python doc :

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If items(), keys(), values(), iteritems(), iterkeys(), and itervalues() are called with no intervening modifications to the dictionary, the lists will directly correspond.

Best thing to do is still to use dict.items()

Pierre Gayvallet
  • 2,933
  • 2
  • 23
  • 37
1

From the Python 2.6 documentation:

Keys and values are listed in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. 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()].

I'm over 99% certain the same will hold true for Python 3.0.

Kathy Van Stone
  • 25,531
  • 3
  • 32
  • 40
  • No need to speculate about Python 3.0. The documentation is here: http://docs.python.org/3.0/library/stdtypes.html#dictionary-view-objects and affirmative. – David Citron Jun 18 '09 at 12:41