如何按键对字典进行排序? [英] How can I sort a dictionary by key?

查看:40
本文介绍了如何按键对字典进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

{2:3, 1:89, 4:5, 3:0}{1:89, 2:3, 3 的好方法是什么:0, 4:5}?
我检查了一些帖子,但它们都使用返回元组的排序"运算符.

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}?
I checked some posts but they all use the "sorted" operator that returns tuples.

推荐答案

标准 Python 词典是无序的(直到 Python 3.7).即使您对 (key,value) 对进行了排序,您也无法以保留顺序的方式将它们存储在 dict 中.

Standard Python dictionaries are unordered (until Python 3.7). 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.

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

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

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)])

没关系od 的打印方式;它会按预期工作:

Never mind the way od is printed out; 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 用户,需要使用 .items() 而不是 .iteritems():

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

这篇关于如何按键对字典进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆