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

1

1 Answer 1

3

You can use collections.OrderedDict for that purpose:

>>> from collections import OrderedDict
>>> OrderedDict(sorted(d.items(), key=lambda x: x[1], reverse=True))
Sign up to request clarification or add additional context in comments.

1 Comment

You absolutely rock. Thanks alot :) have to wait a few mins but will accept this as answer when I can.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.