A previous stack overflow question on sorting a dictionary by key suggested the following for python 3.6+:
d={2:3,1:89,4:5,3:0}
b=dict(sorted(d.items()))
print(b)
And as expected the output is as follows:
{1: 89, 2: 3, 3: 0, 4: 5}
However when I enter the following
a={'1':1,'x':4,'z':-40023,'c':234}
c=dict(sorted(d.items()))
print(c)
This is the output produced: {'1': 1, 'c': 234, 'x': 4, 'z': -40023
}
My questions are as follows:
The second example is sorted correctly. See the ASCII table to verify that digits come before letters.
Python 3.6 (specifically the CPython implementation) changed the way dictionaries are implemented. A side effect of this change is that dictionaries retain the element insertion order, which can be very handy. This was just a side effect in 3.6, but the BDFL decreed that this change be made a feature of the language beginning with version 3.7.
b
in your code above is indeed a new dict
, and based on item 2 above, insertion order is retained. In this case, items are inserted in sorted order.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.