Reversing the order of key-value pairs in a dictionary (Python) [duplicate]

扶醉桌前 提交于 2021-01-02 06:50:08

问题


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.


回答1:


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

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

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



回答2:


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



回答3:


A dictionary uses Hashmap to store Key and corresponding values.

Look at : Is a Python dictionary an example of a hash table?

Anything related to hash has no order.

You can do it with this:

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() returns a list of tuples : [('a', 1), ('c', 3), ('b', 2), ('d', 4)] and k,v gets the values in tuples to iterate in loop. sorted() returns a sorted list, whereas you cannot use d.items().sort() which does not return, but instead tries to overwrite the d.items().




回答4:


This will work. Based on Venkateshwara's that didn't work for me 'as is'.

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



回答5:


d={"a":1, "b":2, "c":3}
x={}
for i in sorted(d.keys(),reverse=True):
    x[i]=d[i]
print(x)


来源:https://stackoverflow.com/questions/32110199/reversing-the-order-of-key-value-pairs-in-a-dictionary-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!