Re:Python dicts are now ordered
by throwaway287391 on Friday February 07, 2020 @12:27PM
(#22268376)
The property you mention at the end has been true of dicts since long before 3.5, at least since 2.7 if not forever. See https://docs.python.org/2/library/stdtypes.html#dict.items :
> 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()).
Sorry, yes, I was hasty. Ordered dicts supports such a thing with intervening modifications:
oldkeys = list(D.keys())
D[z] = foo(z)
now if you take zip(oldkeys, D.values())
then you're guaranteed to iterate over oldkeys, with the proper values associated with those keys -- if z was an oldkey, its value got updated; otherwise, it comes after oldkeys and gets dropped out of zip.The subtlety of this is what I, and perhaps others, find the most jarring.
Dicts are ordered, specifically insertion-ordered, not sorted.
Sometimes they'll be sorted:
... specifically, when you insert them in sorted order. But then you can break the sortedness on your next insert: What it allows is parallel iteration: now being synonymous with This enables, nay, encourages people to write code that is very subtly broken in 3.5 and below.