dict.keys() and dict.values() are always the same order, is it?

Cameron Simpson cs at zip.com.au
Tue Apr 20 05:52:04 CEST 2010


On 20Apr2010 11:03, Menghan Zheng <menghan412 at gmail.com> wrote:
| Is it assured the following statement is always True?
| If it is always True, in which version, python2.x or python3.x?
| 
| >>> a = dict()
| ...
| >>> assert(a.values == [a[k] for k in a.keys()])
| --> ?

It is always true. At this URL:

  http://docs.python.org/library/stdtypes.html?highlight=values#dict.items

it says:

  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()).

BTW, I got to that particular piece of text by starting at the doco for
the .values() method of "dict", which links to the .items() method.

Cheers,
-- 
Cameron Simpson <cs at zip.com.au> DoD#743
http://www.cskk.ezoshosting.com/cs/

I couldn't think of anything else to do with it, so I put it on the web.



More information about the Python-list mailing list