0

I am relatively new with python so I apologize if approaching a stupid way.

Basically I have a bunch of json data that has variable keys. These represent statistics. I am trying to sort the data from highest to lowest to show what has been used the most.

JSON EX:

{
    "key1" : 10,
    "key2" : 35,
    "key3" : 5
}

Desired Output:

{
    "key2" : 35,
    "key1" : 10,
    "key3" : 5
}

So what I currently have is:

def single_val(data):
sorted_values = {'default': -10}
keys = map(str, data.keys())

for i in range(len(data)):
    if(i == 0):
        sorted_values[keys[0]] = sorted_values.pop('default')
        sorted_values[keys[0]] = data[keys[0]]
    else:
        if(sorted_values.values()[i - 1] < data[keys[i]]):
            sorted_values[keys[i]] = sorted_values.pop(keys[i - 1])
            sorted_values[keys[i]] = data[keys[i]]
            sorted_values[keys[i - 1]] = data[keys[i - 1]]
        else:
            sorted_values[keys[i]] = data[keys[i]]

So the problem is this only works for the first 3 or 4 iterations. After that things start coming out of order and just don't work anymore.

The thought process of the above is if the new value is less than the prev it should be the prev and the prev should be the new. This isn't really happening.

So any ideas on how I can approach this?

EDIT:

Just wanted to add, the above json shows the keys basically incrementing sequentially but in my application I might have keys like:

waffle juice tea eggs chips

So they are completely 'random'.

basic
  • 3,348
  • 3
  • 21
  • 36
  • Possible duplicate of [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – Sraw Jan 12 '19 at 02:15

1 Answers1

3

You can use collections.OrderedDict for that purpose:

>>> from collections import OrderedDict
>>> OrderedDict(sorted(d.items(), key=lambda x: x[1], reverse=True))
a_guest
  • 34,165
  • 12
  • 64
  • 118
  • You absolutely rock. Thanks alot :) have to wait a few mins but will accept this as answer when I can. – basic Jan 12 '19 at 02:16