2015-12-06 79 views
0

打印具有相同值的多个字典密钥,因此可以说我有一个包含不同密钥的多个最大值的字典。我试图使用代码:如何使用max()函数

taste = {"Mussels": 4, "Limpets": 4, "Prawn": 2, "Plankton":1} 
    print(max(taste, key=taste.get)) 

但它只给我贻贝或贝特,这取决于哪一个先来。我试图设置的最高值,然后通过我的钥匙,并为每个键重复,我的价值观如:

highest = max(taste.values()) 
    for i in taste.keys(): 
     for j in taste[i]: 
     if j == highest: 
      print(i) 

但似乎没有工作,因为你无法通过像在我的字典中的值的整数interate 。那么最干净和最简单的方法是做什么

+0

你想要什么作为输出'[[“Mussel s“],[Limpets]]或其中任何一个以任意(随机)顺序? – ZdaR

+2

你只想'如果味道[我] ==最高',当然? – jonrsharpe

回答

0

你可以使用列表解析。

>>> taste = {"Mussels": 4, "Limpets": 4, "Prawn": 2, "Plankton":1} 
>>> highest = max(taste.values()) 
>>> [k for k, v in taste.items() if v == highest] 
['Limpets', 'Mussels'] 

>>> for i in taste.keys(): 
...  if taste[i] == highest: 
...   print(i) 
... 
Limpets 
Mussels 
0

因为你已经是最大的集多个值,你需要在一个位聪明的你是如何筛选出所有具有相同值的键。

这是更多的排序操作,而不是最大操作。

>>> taste = {"Mussels": 4, "Limpets": 4, "Prawn": 2, "Plankton":1} 
>>> ordered_by_rating = sorted(list(taste.items()), key=lambda x: x[1], reverse=True) 
>>> top_rating = max(ordered_by_rating, key=lambda x: x[1])[1] 
>>> only_top = [x[0] for x in filter(lambda x: x[1] == top_rating, ordered_by_rating)] 
>>> only_top 
['Mussels', 'Limpets'] 

您可以压缩以上,通过降低循环的数量,你必须要经过:

>>> [k for k,v in taste.items() if v == max(taste.values())] 
['Mussels', 'Limpets'] 
1

这是我会做什么:

highest_value = max(taste.itervalues()) 
print [key for key, value in taste.iteritems() if value == highest_value] 
0

该解决方案是使用Python3:

maxkeys = [k for k, v in taste.items() if v == max(taste.values())]