【问题标题】:python sort the dictionary based on valuespython根据值对字典进行排序
【发布时间】:2019-03-06 10:54:33
【问题描述】:

我有一个 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的方式吗? 任何帮助都非常感谢?

【问题讨论】:

标签: python dictionary


【解决方案1】:

试试下面的代码:

x = [{"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}]

newlist = sorted(x, key=lambda k: int(k['value']),reverse = True) 
for i in newlist:
    del i['value']

【讨论】:

  • newlist = sorted(benefits, key=lambda k: k['value'],reverse = True)
  • TypeError: 字符串索引必须是整数
  • 值的类型必须是整数
  • 请用你的建议参考我更新的问题。我遇到了同样的错误。
【解决方案2】:
df_benefits.sort(['MULTIPLIER'],ascending=True)
df_benefits.drop(columuns='value')

如果您在将其转换为字典之前运行它,它应该被排序并且没有值。

你应该另外删除 for 循环中的“值”

更新

【讨论】:

【解决方案3】:

也许您可以尝试定义一个函数来对您的字典进行排序:

def sort_dic(d):
    for key, value in sorted(sorted(d.items()), key=itemgetter(1), reverse=True):
yield key, value

或者

def sort_dic(d):
    for key, value in sorted(d.items(), key=lambda a: (-a[1], a[0])):
        yield key, value

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-27
    • 2011-12-11
    相关资源
    最近更新 更多