简体   繁体   中英

python sort the dictionary based on values

I have a csv loaded into pandas dataframe as below :

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

I have the below code to create dictionary :

   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

When called as

benefits = cc_benefits(df_benefit)
benefits['A']

returns :

[{'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}]

But I wanted it in sorted order (by “value” and remove “value” and display as)

[{'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'}]

I am not sure, if its possible ? Also needed a pythonic way of doing it ? Any help is highly appreciated ?

df_benefits.sort(['MULTIPLIER'],ascending=True)
df_benefits.drop(columuns='value')

if you run this before converting it to dictionary it should be sorted and without values.

you should additionally remove 'values' in for loop

Updated

Try the below code:

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

Maybe you could try defining a function to sort your dictionary :

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

Or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM