程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

How to sort nested dictionaries in lists in Python

編輯:Python

data

The data style is as follows , Nested dictionary for list

example = [
{
'id':1,'name':'b'},
{
'id':2,'name':'a'}
]

Although the basic principles have been understood , Still want to be wordy , In computer language , There is such a logical relationship

>>> 2 > 1
True
>>> 'a' < 'b'
True

sorted+lambda

Can solve your worries

  • Use key Parameter determines the sort field
    - So pass in the list elements , That is, the field , Let's go back to the dictionary [key], That's the value
  • Use reverse Parameters determine ascending and descending order
  1. according to id Ascending
>>> sorted(example,key=lambda x:x['id'],reverse=False)
[{
'id': 1, 'name': 'b'}, {
'id': 2, 'name': 'a'}]
  1. according to id Descending
>>> sorted(example,key=lambda x:x['id'],reverse=True)
[{
'id': 2, 'name': 'a'}, {
'id': 1, 'name': 'b'}]
  1. according to name Ascending
>>> sorted(example,key=lambda x:x['name'],reverse=False)
[{
'id': 2, 'name': 'a'}, {
'id': 1, 'name': 'b'}]
  1. according to name Descending
>>> sorted(example,key=lambda x:x['name'],reverse=True]
[{
'id': 1, 'name': 'b'}, {
'id': 2, 'name': 'a'}]

Tips

  • sorted Will not change the original array , So you need to assign values to new variables
    After the operation just now , The original example The variable output is followed by
>>> example
[{
'id': 1, 'name': 'b'}, {
'id': 2, 'name': 'a'}]

There was no change

  • lambda Functions are easy to confuse for beginners , You can take shorthand like this

lambda Pass in the parameter : Output results

Equivalent to

def Isn't there a name ( Pass in the parameter ):
return Output results

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved