python - 尝试使用插入排序对字典列表及其子项的值进行排序(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”对象不可下标
解决方案
sortedScores = sorted([dictionary1,dictionary2,dictionary3],key=lambda x:int(x['timestamp']),reverse=True)
推荐阅读
- javascript - 输入 addEventListener - 点击有效,onchange/oninput 无效
- regex - 匹配法语字符
- python - 如何在使用已删除项目创建另一个列表时从列表中删除项目?
- c# - Cosmos DB 调用永远不会通过异步调用返回
- c# - 根据 form_Load() 函数推进条形进度
- sql - oracle 中关于 HUGECLOB 的详细信息
- c - 如何修复结构数组指针重新分配的错误?
- r - 如何使用场景向 scatter3D Plotly 绘图添加注释?
- c# - 如何在运行时编译的类中使用编译时类?
- struct - 返回一个在 Julia 中更改了字段的新结构