社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

python排序字典列表

VengaVenga • 6 年前 • 1288 次点击  

我有一个字典列表:

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描述的简单任务:按组合排序\uRef asc,百分比描述

我的尝试没有成功:

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

给我

KeyError: 1

第二次尝试:

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

不能按百分比排序。

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/30637
 
1288 次点击  
文章 [ 2 ]  |  最新文章 6 年前
Prune
Reply   •   1 楼
Prune    6 年前

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

您的第二次尝试是不足的,只是因为您没有辅助排序键。

jpp
Reply   •   2 楼
jpp    6 年前

你可以使用 dict.__getitem__ 或者它的句法糖 [] :

res = sorted(AccountValues, key=lambda x: (x['portfolio_ref'], -x['percent']))

请记住,字典不能通过整数进行索引。历史上(3.6之前),它们甚至没有被订购。即使在Python3.7中,也不能直接提取 n th键或值。

结果:

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