python - python根据值对字典进行排序
问题描述
我有一个 csv 加载到 pandas 数据框中,如下所示:
TYPE BENEFIT_CATEGORY FORMULA TEXT_1 MULTIPLIER TEXT_2
A MATH Y You can earn up to 50 Rs per year
A SCIENCE Y You can earn up to 100 Rs per year
A TOTAL Y You can earn up to 200 Rs per year
A SOCIAL Y You can earn up to 50 Rs per year
B SOCIAL Y You can earn up to 20 Rs per year
B MATH Y You can earn up to 10 Rs per year
B TOTAL Y You can earn up to 30 Rs per year
我有以下代码来创建字典:
def cc_benefits(df_benefit):
benefits = {}
for row in df_benefit.itertuples():
if row.FORMULA == 'N':
description = str(row.TEXT_1)
else:
string = str(row.TEXT_1)
formula = row.MULTIPLIER
description = string + " " + str(formula) + " " + str(row.TEXT_2)
if row.TYPE in benefits:
benefits[row.TYPE].append({
'Name': row.BENEFIT_CATEGORY,
'Description': description,
'value' : formula
})
else:
benefits[row.TYPE] = [
{
'Name': row.BENEFIT_CATEGORY,
'Description': description,
'value' : formula
}
]
# as suggested by @skaul
benefits = sorted(benefits, key=lambda k: int(k['value']),reverse = True)
for i in benefits:
del i['value']
# as suggested by @skaul
return benefits
当被称为
benefits = cc_benefits(df_benefit)
benefits['A']
返回:
[{'Name': 'MATH',
'Description': 'You can earn up to 50 Rs per year',
'value': 50},
{'Name': 'SCIENCE',
'Description': 'You can earn up to 100 Rs per year',
'value': 100},
{'Name': 'TOTAL',
'Description': 'You can earn up to 200 Rs per year',
'value': 200},
{'Name': 'SOCIAL',
'Description': 'You can earn up to 50 Rs per year',
'value': 50}]
但我希望它按排序顺序(按“值”并删除“值”并显示为)
[{'Name': 'TOTAL',
'Description': 'You can earn up to 200 Rs per year'},
{'Name': 'SCIENCE',
'Description': 'You can earn up to 100 Rs per year'},
{'Name': 'MATH',
'Description': 'You can earn up to 50 Rs per year'},
{'Name': 'SOCIAL',
'Description': 'You can earn up to 50 Rs per year'}]
我不确定,如果可能的话?还需要一种pythonic的方式吗?任何帮助都受到高度赞赏?
解决方案
df_benefits.sort(['MULTIPLIER'],ascending=True)
df_benefits.drop(columuns='value')
如果您在将其转换为字典之前运行它,则应该对其进行排序并且没有值。
您还应该在 for 循环中删除“值”
更新
推荐阅读
- c# - 浮点数如何保持这个值?1571563892。在范围内,但改为1571564000,多出12个
- java - Maven 构建无法在 jenkins websphere 部署插件中部署
- powershell - 如何使用 PowerShell 获取恶意 DHCP 客户端?
- javascript - 如何同时处理:一个 dom 元素的 onClick 和 onMouseMove?
- java - 处理此 REST API 端点错误的最佳方法是什么?
- c++ - 为什么 SDL_PollEvent 这么慢?
- azure - Azure IoT Hub Jobs 和 Azure IoT 自动设备管理之间的区别
- kubernetes - 在 CI/CD 管道实施中管理 Kubernetes 部署的创建和更新
- xcode - Xcode 11 comments formatting
- jenkins - 新的詹金斯版本,当我使用构建流时构建失败,缺少构建历史