[英]Python sort list of dictionaries
I have a list of dictionaries: 我有一个词典列表:
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} ]
Simple mission per SQL description: Order by portfolio_ref ASC, percent DESC 每个SQL描述的简单任务:按portfolio_ref ASC排序,DESC百分比
What I tried unsuccessfully: 我尝试失败了:
sorted(AccountsValues, key=lambda x: (x[1],-x[4]))
which gives me 这给了我
KeyError: 1
Second attempt: 第二次尝试:
import operator
result = sorted(myAccountsValues, key=itemgetter('percent'))
which fails to sort on percentage. 没有按百分比排序。
You can use dict.__getitem__
or its syntactic sugar []
: 你可以使用
dict.__getitem__
或其语法糖[]
:
res = sorted(AccountValues, key=lambda x: (x['portfolio_ref'], -x['percent']))
Remember that dictionaries are not indexable by integers. 请记住,字典不能通过整数编制索引。 Historically (pre-3.6), they are not even ordered.
历史上(3.6之前),它们甚至没有订购。 Even in Python 3.7, you cannot directly extract the n th key or value.
即使在Python 3.7中,也无法直接提取第n个键或值。
Result: 结果:
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}]
You just have to combine all the things you did correctly: sort keys as a tuple and the proper way of referencing a dict
entry: 您只需要将所有正确组合的东西组合在一起:将键排序为元组以及引用
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'}]
Better yet, use 更好的是,使用
sorted(AccountValues, key=itemgetter("portfolio_ref", "percent"))
Your first attempt failed because x[1]
and x[4]
are not valid references into the dictionaries: you have to use the labels you originally gave, not relative positions. 您的第一次尝试失败,因为
x[1]
和x[4]
不是对词典的有效引用:您必须使用最初给出的标签,而不是相对位置。
Your second attempt is deficient only because you don't have the secondary sort key. 您的第二次尝试仅仅是因为您没有辅助排序键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.