Python 对字典列表进行排序

标签 python list sorting dictionary

我有一个字典列表:

AccountValues = [
{'portfolio_ref': 1, 'tag': 'FullInit', 'value': '20642.95', 'currency': 'USD', 'percent': 0.0}, 
{'portfolio_ref': 1, 'tag': 'FullMaint', 'value': '21350.54', 'currency': 'USD', 'percent': 0.0}, 
{'portfolio_ref': 1, 'tag': 'NetLiq', 'value': '70976.05', 'currency': 'USD', 'percent': 100.0} ]

根据 SQL 描述执行简单任务:按 Portfolio_ref ASC、百分比 DESC 排序

我尝试失败的方法:

sorted(AccountsValues, key=lambda x: (x[1],-x[4]))

这给了我

KeyError: 1

第二次尝试:

import operator
result = sorted(myAccountsValues, key=itemgetter('percent'))

无法按百分比排序。

最佳答案

您可以使用dict.__getitem__或其语法糖[]:

res = sorted(AccountValues, key=lambda x: (x['portfolio_ref'], -x['percent']))

请记住,字典不能按整数索引。从历史上看(3.6 之前),它们甚至没有被排序。即使在 Python 3.7 中,您也无法直接提取第 n 个键或值。

结果:

print(res)

[{'portfolio_ref': 1, 'tag': 'NetLiq', 'value': '70976.05', 'currency': 'USD', 'percent': 100.0},
 {'portfolio_ref': 1, 'tag': 'FullInit', 'value': '20642.95', 'currency': 'USD', 'percent': 0.0},
 {'portfolio_ref': 1, 'tag': 'FullMaint', 'value': '21350.54', 'currency': 'USD', 'percent': 0.0}]

关于Python 对字典列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52507652/

相关文章:

java - 按日期属性对对象列表进行排序

python - 未使用 scrapy 以 XML 或 JSON 形式抓取数据

python - 将具有相应参数的函数列表传递给另一个函数

python - 如何使用 matplotlib 渲染 latex 矩阵

python - 使用 Beautiful Soup 提取 css 链接

python - 如何从 3 个列表中制作字典

Python - 转置各种长度列表的列表 - 3.3 最简单​​的方法

python - 列表理解与元组赋值

c - 我如何执行插入排序但检查数组中元素的属性而不仅仅是元素?

jquery - 根据元素的数据属性对 div 进行排序