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