簡體   English   中英

Python排序詞典列表

[英]Python sort 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} ]

每個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}]

您只需要將所有正確組合的東西組合在一起:將鍵排序為元組以及引用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]不是對詞典的有效引用:您必須使用最初給出的標簽,而不是相對位置。

您的第二次嘗試僅僅是因為您沒有輔助排序鍵。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM