反转字典中键/值对的顺序(Python) [英] Reversing the order of key-value pairs in a dictionary (Python)

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

问题描述

如何在Python中颠倒字典的键值对的顺序?例如,我有这本字典:

How do I reverse the order of key-value pairs of a dictionary, in Python? For example, I have this dictionary:

{"a":1, "b":2, "c":3}

我想反转它,以便返回:

I want to reverse it so that it returns:

{"c":3, "b":2, "a":1}

有没有我听说过的功能可以做到这一点?一些代码行也可以.

Is there a function that I haven't heard about that can do this? Some lines of code is fine as well.

推荐答案

字典没有任何顺序感,因此您的键/值对不以任何格式排序.

Dictionary does not have any sense of order , so your key/value pairs are not ordered in any format.

如果要保留键的顺序,则应使用从一开始就是 collections.OrderedDict ,而不是使用普通字典,示例-

If you want to preserve the order of the keys, you should use collections.OrderedDict from the start, instead of using normal dictionary , Example -

>>> from collections import OrderedDict
>>> d = OrderedDict([('a',1),('b',2),('c',3)])
>>> d
OrderedDict([('a', 1), ('b', 2), ('c', 3)])

OrderedDict将保留键在字典中输入的顺序.在上述情况下,这就是键在列表中的存在顺序- [('a',1),('b',2),('c',3)] -'a'->'b'->'c'

OrderedDict would preserve the order in which the keys were entered into the dictionary. In above case, it would be the order in which the keys existed in the list - [('a',1),('b',2),('c',3)] - 'a' -> 'b' -> 'c'

然后您可以使用 reversed(d)(示例-

Then you can get the reversed order of keys using reversed(d) , Example -

>>> dreversed = OrderedDict()
>>> for k in reversed(d):
...     dreversed[k] = d[k]
...
>>> dreversed
OrderedDict([('c', 3), ('b', 2), ('a', 1)])

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

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