A method for sorting python dictionary values and extracting the previous n key values

  • 2020-12-19 21:08:22
  • OfStack

Today, in the process of writing an algorithm, I got a dictionary similar to the following:


{'user1':0.456,'user2':0.999,'user3':0.789,user:'0.234'}

To get the first 3 key values in the dictionary, the following code is generated

Post code directly:


def order_dict(dicts, n):
 result = []
 result1 = []
 p = sorted([(k, v) for k, v in dicts.items()], reverse=True)
 s = set()
 for i in p:
  s.add(i[1])
 for i in sorted(s, reverse=True)[:n]:
  for j in p:
   if j[1] == i:
    result.append(j)
 for r in result:
  result1.append(r[0])
 return result1

A similar problem

python, how to pick the corresponding key value according to value value in the dictionary,

Such as:


dic = { ' user1':'01',  ' user2':'02'} 

You need to input 01 to get a


list(dic.keys())[list(dic.values()).index('01')]

In Python, the keys corresponding to the maximum/minimum values in the dictionary are obtained:

1. Use min(dict, key= ES31en.get) or max(dict, key= ES36en.get)


d = {1:1, 2:0, 3:2}
min(d, key=d.get) // The minimum  
max(d, key=d.get) // The biggest 

2. Use lambda function


min(d.items(), key=lambda x: x[1]) 
min(d, key=lambda x: d[x])

Related articles: