Sort list of nested dictionaries in python

I have something like

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

And you will need:

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

Many thanks!

EDIT: I would like to sort by subkey1, this was unclear earlier.

+7
source share
3 answers

Use the key keyword for the sorted() and sort() functions:

 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 considered a dictionary with a subkey key.

See the Python Sorting HOWTO for more details and tricks.

+12
source
 sorted(yourdata, reverse=True) 
0
source

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

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

All Articles