Why is dictionary.keys() a list and not a set?

bonono at gmail.com bonono at gmail.com
Thu Nov 24 04:42:42 CET 2005


Peter Hansen wrote:
> 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?
Thanks, but yes and no.

Which is also my initial puzzle, items() and iteritems() already gives
you the tuples, why such gurantee or the others ? Doesn't that violate
the general idiom that if we can do certain thing in one way, there
better be one and only one way.

Are there other usage scenarios that would be benefit from this as the
example given is not convincing for me.




More information about the Python-list mailing list