Python字典排序列表

时间:2018-09-25 22:54:33

标签: python list sorting dictionary

我有一个词典列表:

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

每个SQL描述中的简单任务:按Portfolio_ref ASC,DESC百分比排序

我尝试失败的地方:

KeyError: 1

这给了我

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

第二次尝试:

{{1}}

无法按百分比排序。

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:1)

您只需要将所有正确完成的事情组合在一起:将键排序为元组,并且是引用dict条目的正确方法:

>>> sorted(AccountValues, key=lambda x: (x["portfolio_ref"], -x["percent"]))
[{'tag': 'NetLiq', 'portfolio_ref': 1, 'value': '70976.05', 'percent': 100.0, 'currency': 'USD'},
 {'tag': 'FullInit', 'portfolio_ref': 1, 'value': '20642.95', 'percent': 0.0, 'currency': 'USD'},
 {'tag': 'FullMaint', 'portfolio_ref': 1, 'value': '21350.54', 'percent': 0.0, 'currency': 'USD'}]

更好,使用

sorted(AccountValues, key=itemgetter("portfolio_ref", "percent"))

您的第一次尝试失败了,因为x[1]x[4]不是对字典的有效引用:您必须使用最初给出的标签,而不是相对位置。

您的第二次尝试是有缺陷的,仅是因为您没有辅助排序键。