Sort list of dicts by multiple values [duplicate]

拜拜、爱过 提交于 2020-06-23 01:56:21

问题


I have the following dict

tempdata = {'logs': [
    {'starttime':'901',
     'time':'5'
     },
    {'starttime':'902',
     'time':'3'
     },
    {'starttime':'900',
     'time':'2'
     },    
    {'starttime':'901',
     'time':'2'
     },
    {'starttime':'905',
     'time':'1'
     },
    {'starttime':'904',
     'time':'1'
     }
]
}

I want to primarily sort by starttime. Which I do perfectly with:

 tempdata['logs'] = sorted(tempdata['logs'],key=lambda k: k['starttime'])

But now, I want to sort them by time as well.

Expected output:

tempdata = {'logs': [
    {'starttime':'900',
    'time':'2'
    },
    {'starttime':'901',
     'time':'2'
     },
    {'starttime':'901',
     'time':'5'
     },
    {'starttime':'902',
     'time':'3'
     },
    {'starttime':'904',
     'time':'1'
     },
    {'starttime':'905',
     'time':'1'
     }
]
}

How can I accomplish this task? I've looked up the sorted(), and can't find what I'm looking for.


回答1:


Sort them using a tuple as a key like this:

tempdata['logs'] = sorted(tempdata['logs'],
                          key=lambda k: (k['starttime'], k['time']))

Tuples are compared by each element in order.

And as a side note, this way the values are compared as strings, not as numbers. Don't know if that's relevant for you.



来源:https://stackoverflow.com/questions/38789544/sort-list-of-dicts-by-multiple-values

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!