use set notation for repr of dict_keys?

Chris Angelico rosuav at gmail.com
Wed Feb 24 00:40:32 EST 2021


On Wed, Feb 24, 2021 at 4:29 PM Random832 <random832 at fastmail.com> wrote:
>
> AIUI the keys, values, and items collections have always had the ordering guarantee that iterating over them while not modifying the underlying dictionary will give the same order each time [with respect to each other, and possibly also with respect to iterating over the original dictionary to obtain the keys]
>

Correct, on all counts. I believe the old guarantee (before insertion
order was maintained) was that *any* change could change the iteration
order, but that .items(), .keys(), and .values() (and their iter*
counterparts) would always change together. But in practice, I believe
this kind of code has always been safe:

for key in some_dict:
    some_dict[key] += 1

I can't find anywhere in the docs that says that changes to *values*
(without changing the set of keys) won't change iteration order, but
given how common this kind of code is, I would expect that it's at
least a de facto guarantee.

ChrisA


More information about the Python-list mailing list