根据键的值显示字典中最大的项?

时间:2018-12-10 13:28:21

标签: python python-3.x dictionary key

我有一个字典,我想显示三个最大的项目,但我希望它基于键的int值。这是代码:

cust_numb = int(input("Enter number of unique customers then press enter:"))
list_customer = {}
customers = 1
for y in range(0,cust_numb):
    purch_numb = int(input("How many purchases did customer %s have % 
(customers)))
    list_customer.update({"customer{}".format(customers) : purch_numb})
    customers = customers + 1

info = ""
for customer in range(0,cust_numb):
    info += "%s " % ("customer {}".format(customer+1)) + "had %s " % 
(list_customer["customer{}".format(customer+1)]) + "purchases. "

info = dict(dictionary)

我无法在线找到它,我们将为您提供任何帮助!

1 个答案:

答案 0 :(得分:0)

没有直接的方法,因为在这种情况下通常不使用字典。它需要一些列表理解或其他解决方法。下面是一种方法,该方法形成一个排序的值列表,然后获取与这些排序的值列表相对应的键。

d     = {'a':2,'b':1,'c':5,'d':0}
sList = sorted(d.values())
op    = []
for i in sList:
  op.append([k for k,v in d.items() if v == i][0])
print (op)