Python字典中的键顺序 [英] Order of keys in Python dictionary

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

问题描述

我有一个字典

{'a': 'first', 'b': 'second'}

但是,我需要以不同的顺序排列字典:

However, I need the dictionary in a different order:

{'b': 'second', 'a': 'first'}

这是最好的方式是什么?

What is the best way to do this?

推荐答案

字典是 / strong>即可。所以没有办法做到这一点。

Dictionaries are not ordered. So there is no way to do it.

如果你有python2.7 +,你可以使用 collections.OrderedDict - 在这种情况下,您可以使用 .items()检索项目列表,然后将其反转并创建一个新的 OrderedDict 从相反的列表中:

If you have python2.7+, you can use collections.OrderedDict - in this case you could retrieve the item list using .items() and then reverse it and create a new OrderedDict from the reversed list:

>>> od = OrderedDict((('a', 'first'), ('b', 'second')))
>>> od
OrderedDict([('a', 'first'), ('b', 'second')])
>>> items = od.items()  # list(od.items()) in Python3
>>> items.reverse()
>>> OrderedDict(items)
OrderedDict([('b', 'second'), ('a', 'first')])

如果您使用的是较旧的python版本,您可以从 http://code.activestate.com/recipes/576693/

If you are using an older python version you can get a backport from http://code.activestate.com/recipes/576693/

这篇关于Python字典中的键顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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