简体   繁体   中英

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.

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'}}]

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