Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

python - 如何按键对字典排序?(How can I sort a dictionary by key?)

What would be a nice way to go from {2:3, 1:89, 4:5, 3:0} to {1:89, 2:3, 3:0, 4:5} ?

(从{2:3, 1:89, 4:5, 3:0}{1:89, 2:3, 3:0, 4:5}什么?)
I checked some posts but they all use the "sorted" operator that returns tuples.

(我检查了一些帖子,但它们都使用了返回元组的“排序”运算符。)

  ask by Antony translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Standard Python dictionaries are unordered.

(标准Python字典是无序的。)

Even if you sorted the (key,value) pairs, you wouldn't be able to store them in a dict in a way that would preserve the ordering.

(即使您对(键,值)对进行了排序,也无法以保留顺序的方式将它们存储在dict中。)

The easiest way is to use OrderedDict , which remembers the order in which the elements have been inserted:

(最简单的方法是使用OrderedDict ,它可以记住元素插入的顺序:)

In [1]: import collections

In [2]: d = {2:3, 1:89, 4:5, 3:0}

In [3]: od = collections.OrderedDict(sorted(d.items()))

In [4]: od
Out[4]: OrderedDict([(1, 89), (2, 3), (3, 0), (4, 5)])

Never mind the way od is printed out;

(没关系od的打印方式;)

it'll work as expected:

(它会按预期工作:)

In [11]: od[1]
Out[11]: 89

In [12]: od[3]
Out[12]: 0

In [13]: for k, v in od.iteritems(): print k, v
   ....: 
1 89
2 3
3 0
4 5

Python 3 (Python 3)

For Python 3 users, one needs to use the .items() instead of .iteritems() :

(对于Python 3用户,需要使用.items()而不是.iteritems() :)

In [13]: for k, v in od.items(): print(k, v)
   ....: 
1 89
2 3
3 0
4 5

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...