-3

This question has been asked many times, and I searched diligently to no avail. Here is an example of my question:

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

The output I am looking for is as below:

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

I am really unsure how to attack this, as here is my current code:

def reorder(a):
       clean = {}
       pair = {}
       i = 0
       for k, v in a.iteritems():
             pair = a.popitem()
             #Do stuff here
       return clean

What I am currently doing is grabbing the tuple pair as a key/value, as these need to remain the same. I am not sure how to insert this pair in a reverse order though.

Idos
  • 15,053
  • 14
  • 60
  • 75
John Doe
  • 1
  • 2
  • 1
    Your diligent search missed [this question](http://stackoverflow.com/questions/6083531/order-of-keys-in-python-dictionary). –  Jun 16 '16 at 18:08

2 Answers2

0

A dictionary is unordered by definition:

It is best to think of a dictionary as an unordered set of key: value pairs, with the requirement that the keys are unique (within one dictionary).

Therefore, your question cannot be answered and you should consider using a different data structure. Perhaps an OrderedDict which can be reversed:

>>> import collections
>>> dict = collections.OrderedDict([(1,2),(3,4),(5,6)])
>>> collections.OrderedDict(reversed(list(dict.items())))
OrderedDict([(5, 6), (3, 4), (1, 2)])
Idos
  • 15,053
  • 14
  • 60
  • 75
  • Thank you very much for a seriously fast answer. Unfortunately at this time, I can't change the data structure but its starting to sound as if this is quite impossible to do. Can this be done manually? I was thinking up above in my code, is to grab the tuple, and send it to another function. Use that function to store the tuple in memory, assign it to a value such as 0, 1, 2, 3 and use a for loop to insert the tuples backwards into a new dictionary – John Doe Jun 16 '16 at 15:31
  • 1
    As I said, there is **no possible way** to keep using a dictionary and "reverse" it, because the word "reverse" has no meaning in a dictionary... You can put the items in a `list` and reverse that, if it helps... – Idos Jun 16 '16 at 15:32
  • What about creating a new dict and having the key/value pairs inserted in a specified way? – John Doe Jun 16 '16 at 15:43
  • 2
    You are trying to eat soup with a fork... Please take my advice. – Idos Jun 16 '16 at 15:44
0

Firstly, the dict object of python is a hashtable, so It have no order. but if you only want to get a list is order you can use sorted(iterable, key=None, reverse=False) method. def order(dic): return sorted(dic.items(),key=lambda x:x[1],reverse=True)

agnewee
  • 100
  • 7