简体   繁体   中英

python: is it possible to sort a dictionary by key?

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:

  1. Why does this approach work for the first case and not the second.
  2. Why does it only work for python3.6+ and not before. Did they change the implementation of the dictionary class?
  3. Is b in the above code a new sorted dictionary and if so how is that possible as I learned that hashtables are never ordered?
  1. The second example is sorted correctly. See the ASCII table to verify that digits come before letters.

  2. 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.

  3. 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM