首页 > 解决方案 > 尝试使用插入排序对字典列表及其子项的值进行排序(python)

问题描述

我的字典来自数据库,但对于这个例子,假设我有两个字典

    dictionary1 = {
        "score": str(percentageScore),       #totalScore
        "date": str(today),      #today
        "title": str(title),   #title
        "timestamp": str(timestamp)  #timestamp to display results in order
    }

时间戳是一个整数,我想用它来对包含多个这样的字典的python列表进行排序,根据时间戳整数降序排列。

我试图这样做:

sortedScores = [dictionary1, dictionary2, dictionary3]

            for i in range(1, len(sortedScores)):
                sortKey = sortedScores[i['timestamp']]
                j = (i - 1)
                while (j <= 0) and (sortKey < (sortedScores[j])['timestamp']):
                    sortedScores[j+1] = sortedScores[j]
                    j -= 1
                sortedScores[j+1] = sortKey

但是我目前收到错误

TypeError:“int”对象不可下标

标签: pythonalgorithmsorting

解决方案


sortedScores = sorted([dictionary1,dictionary2,dictionary3],key=lambda x:int(x['timestamp']),reverse=True)


推荐阅读