我有一个字典列表:
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/