字典中的键顺序 [英] Order of keys in dictionary
本文介绍了字典中的键顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有字典
{'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?
推荐答案
字典未排序.所以没有办法.
如果您使用的是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/
这篇关于字典中的键顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文