15

I have something like

[
    {
        "key": { "subkey1":1, "subkey2":"a"  }
    },
    {
        "key": { "subkey1":10, "subkey2":"b" }
    },
    {
        "key": { "subkey1":5, "subkey2":"c" }
    }
]

And would need to have :

[
    {
        "key": { "subkey1":10, "subkey2":"b" }
    },
    {
        "key": { "subkey1":5, "subkey2":"c" }
    },
    {
        "key": { "subkey1":1, "subkey2":"a" }
    }
]

Many thanks!

EDIT : I'd like to sort by subkey1, this wasn't clear previously.

3 Answers 3

21

Use the key keyword to the sorted() function and sort() method:

yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)

Demo:

>>> yourdata = [{'key': {'subkey': 1}}, {'key': {'subkey': 10}}, {'key': {'subkey': 5}}]
>>> yourdata.sort(key=lambda e: e['key']['subkey'], reverse=True)
>>> yourdata
[{'key': {'subkey': 10}}, {'key': {'subkey': 5}}, {'key': {'subkey': 1}}]

This assumes that all top-level dictionaries have a key key, which is assumed to be a dictionary with a subkey key.

See the Python Sorting HOWTO for more details and tricks.

Sign up to request clarification or add additional context in comments.

Comments

3

Assuming you want to sort by the value of d['key']['subkey'] for every dictionary d in the list, use this:

sorted(yourdata, key=lambda d: d.get('key', {}).get('subkey'), reverse=True)

1 Comment

Thanks so much for your answer, it worked on a very complex nested dictionaries list. Take a bow!
-2
sorted(yourdata, reverse=True)

4 Comments

I didn't downvote this, but you'll realise that a dict as an iterable returns the keys, so you won't end up with a useful list
did not understand. the output just like asked.
@alexvassel: The output in the simple example case happens to be the same, but if any of the dictionaries has an extra key in it, the results will be very different indeed. I didn't downvote your answer, but it is incorrect on that account.
What happens sometimes is that the question changes, although it's a valid answer in some sense... I just wouldn't worry about it... ie: you post a working solution, and then all of a sudden the question changes... and your solution doesn't work... Some people will downvote on the slightest off and others will comment that it's not workable and why (I prefer the latter)...

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.