Python字典排序列表

文加·文加

我有一个字典列表:

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'))

无法按百分比排序。

pp

您可以使用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}]

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章