Dictionary sorting

Chris Angelico rosuav at gmail.com
Thu Nov 3 19:59:43 EDT 2011


On Fri, Nov 4, 2011 at 10:01 AM, Tim Chase
<python.list at tim.thechases.com> wrote:
>  list1 = list(d.iterkeys())
>  list2 = list(d.iterkeys())
>  assert list1 == list2
>

There is such a guarantee in Python 2. From
http://docs.python.org/library/stdtypes.html:
"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()]."

Python 3 does things quite differently (with views), and I can't find
a corresponding promise, but I expect that this would still be the
case.

ChrisA



More information about the Python-list mailing list