6

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

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

我想反转它以使其返回:

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

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

4

5 回答 5

7

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

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

>>> 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'

然后你可以使用reversed(d),例如 -

>>> dreversed = OrderedDict()
>>> for k in reversed(d):
...     dreversed[k] = d[k]
...
>>> dreversed
OrderedDict([('c', 3), ('b', 2), ('a', 1)])
于 2015-08-20T05:36:00.483 回答
0
#The dictionary to be reversed
dict = {"key1":"value1","key2":"value2","key3":"value3"}

#Append the keys of the dictionary in a list
list_keys = []
for k in dict.keys():
    list_keys.append(k)

rev_dict = {}
#Traverse through the reversed list of keys and add them to a new dictionary
for i in reversed(list_keys):
    rev_dict[i] = dict[I]
print(rev_dict)

#OUTPUT: {'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}
于 2020-06-24T06:36:03.277 回答
-1

这将起作用。基于 Venkateshwara 的“原样”对我不起作用。

def reverse(self):
    a = self.yourdict.items()
    b = list(a) # cast to list from dict_view
    b.reverse() # actual reverse
    self.yourdict = dict(b) # push back reversed values
于 2018-10-02T07:33:57.977 回答
-1

字典使用 Hashmap 来存储 Key 和相应的值。

看一下:Python字典是哈希表的一个例子吗?

任何与哈希相关的东西都没有顺序。

你可以这样做:

d = {}
d['a']=1
d['b']=2
d['c']=3
d['d']=4
print d
for k,v in sorted(d.items(),reverse = True):
    print k,v

d.items()返回一个元组列表:[('a', 1), ('c', 3), ('b', 2), ('d', 4)]k,v获取元组中的值以在循环中迭代。 sorted()返回一个排序列表,而你不能返回一个不返回的列表,use d.items().sort()而是尝试覆盖d.items().

于 2015-08-20T06:40:24.210 回答
-2
d={"a":1, "b":2, "c":3}
x={}
for i in sorted(d.keys(),reverse=True):
    x[i]=d[i]
print(x)
于 2019-09-05T17:51:55.190 回答