你只需要把你做的所有正确的事情结合起来:把键排序成一个元组
和
正确的引用方法
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]
词典中的引用无效:必须使用最初给出的标签,而不是相对位置。
您的第二次尝试是不足的,只是因为您没有辅助排序键。