Tapashi Talukdar
Tapashi Talukdar

Reputation: 77

Sort a list of dictionary based on dictionary key

I have a list of python dictionary as follows:

[{'k':{'fruit':'apple','flower':'lily'}},
 {'a':{'fruit':'mango','flower':'lotus'}},
 {'e':{'fruit':'peach','flower':'rose'}}]

I want to sort the list based on the dictionary key in the following format.

[{'a':{'fruit':'mango','flower':'lotus'}},
 {'e':{'fruit':'peach','flower':'rose'}},
 {'k':{'fruit':'apple','flower':'lily'}}]

How can I achieve this.Please suggest me.

Upvotes: 1

Views: 72

Answers (1)

falsetru
falsetru

Reputation: 368944

Use list.sort (to sort in-place) or sorted (to get a new sorted list) with key parameter:

>>> lst = [
...     {'k': {'fruit': 'apple', 'flower': 'lily'}},
...     {'a': {'fruit': 'mango', 'flower': 'lotus'}},
...     {'e': {'fruit': 'peach', 'flower': 'rose'}}
... ]
>>> lst.sort(key=lambda d: next(iter(d)))
>>> lst
[{'a': {'fruit': 'mango', 'flower': 'lotus'}},
 {'e': {'fruit': 'peach', 'flower': 'rose'}},
 {'k': {'fruit': 'apple', 'flower': 'lily'}}]

Upvotes: 3

Related Questions