Home > Blockchain >  How to sort on a dictionary w.r.t the list of values
How to sort on a dictionary w.r.t the list of values

Time:11-19

I have 2 values in the list of each dictionary keys, need to sort the dictionary desc on value1 and asc on value2:

dict1={'123126':[100,'DDD'],'123121':[100,'AAA'],'123122':[100,'BBB'],'123123':[101,'CCC']}
dict2 = {key: val for key,val in sorted(dict1.items(), key = lambda ele: ((ele[1][0]),(ele[1][1])), reverse = True)}
print(dict2)

output >>
{'123123': [101, 'CCC'], '123126': [100, 'DDD'], '123122': [100, 'BBB'], '123121': [100, 'AAA']}

but the expected output is

{'123123': [101, 'CCC'], '123126': [100, 'AAA'], '123122': [100, 'BBB'], '123121': [100, 'DDD']}

CodePudding user response:

Only invoke the descending. Naturally, sorting is ascending. SO no need to use that. Hence you could do:

dict(sorted(d.items(),key= lambda x:-x[1][0]))
Out[25]: 
{'123123': [101, 'CCC'],
 '123126': [100, 'AAA'],
 '123122': [100, 'BBB'],
 '123121': [100, 'DDD']}

CodePudding user response:

I solved using below, but I was expecting this to be done in one statement:

dict1={'123126':[100,'DDD'],'123121':[100,'AAA'],'123122':[100,'BBB'],'123123':[101,'CCC']} dict2 = {key: val for key,val in sorted(dict1.items(), key = lambda ele: ele[1][1], reverse = False)} dict3 = {key: val for key,val in sorted(dict2.items(), key = lambda ele: ele[1][0], reverse = True)}

print(dict2) print(dict3)

output {'123121': [100, 'AAA'], '123122': [100, 'BBB'], '123123': [101, 'CCC'], '123126': [100, 'DDD']} Expeceted- dict3 {'123123': [101, 'CCC'], '123121': [100, 'AAA'], '123122': [100, 'BBB'], '123126': [100, 'DDD']}

  • Related