简体   繁体   中英

Python how to sort a list of nested dictionaries by dictionary keys?

I have a list of nested dictionaries, of the form:

list = [{key1: (tuple_value1, tuple_value2)}, {key2: (tuple_value1, tuple_value2)}, {key3: (tuple_value1, tuple_value2)}, ...]

How can I sort this list based on the KEYS in this list? I want the list to be sorted so that the keys are in alphabetical order.

I found an expression that will sort by the values I believe:

newlist = sorted(list_to_be_sorted, key=lambda k: k['name']) 

But I've yet to be successful sorting by the keys.

you can do. This will sort your dict by keys. This is work only on Python 2.7

newlist = sorted(list_to_be_sorted, key=lambda k: k.keys()) 

Try (works for both versions):

>>> lod=[{'b':[1,2,3]},{'a':[4,5,6]}]
>>> sorted(lod,key=lambda x: list(x.keys()))
[{'a': [4, 5, 6]}, {'b': [1, 2, 3]}]
>>> 

Of course this would also work (works for both versions):

>>> lod=[{'b':[1,2,3]},{'a':[4,5,6]}]
>>> lod.sort(key=lambda x: list(x.keys()))
>>> lod
[{'a': [4, 5, 6]}, {'b': [1, 2, 3]}]
>>> 

But for python 2, @ManojJadhav's answer is the best, because it's faster, not using list outside, (this can do a pretty big change with larger dictionaries)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM