Hanzy
Hanzy

Reputation: 414

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.

Upvotes: 1

Views: 995

Answers (2)

U13-Forward
U13-Forward

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

Manoj Jadhav
Manoj Jadhav

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

Related Questions