Why is dictionary.keys() a list and not a set?
peter at engcorp.com
Thu Nov 24 04:28:45 CET 2005
bonono at gmail.com wrote:
> Peter Hansen wrote:
>>I believe it's currently guaranteed that the order of
>>the items in dict.keys() and dict.values() will match (i.e. the index of
>>any key in its list will be the same as the index of the corresponding
>>value in its list).
> Interesting, but why it guaranteed this as functionality wise they are
> two different things and since dict is unordered, there is no need for
> such guarantee, would it be just implementation consequence ?
From the docs (http://docs.python.org/lib/typesmapping.html):
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(a.values(), a.keys())". The same relationship holds for the
iterkeys() and itervalues() methods: "pairs = zip(a.itervalues(),
a.iterkeys())" provides the same value for pairs. Another way to create
the same list is "pairs = [(v, k) for (k, v) in a.iteritems()]".
Does that explain it adequately?
More information about the Python-list