Reputation: 414
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.
Upvotes: 1
Views: 995
Reputation: 71580
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)
Upvotes: 2
Reputation: 1368
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())
Upvotes: 2