如何从python字典中提取具有最大值的项的键和值

如何从python字典中提取具有最大值的项的键和值,python,dictionary,max,Python,Dictionary,Max,下面的代码创建一个电子邮件地址字典,以及每封电子邮件出现的频率。以最大频率提取电子邮件的密钥和值的最佳方法是什么 fname = input("Enter file:") try: fhand = open(fname) except: print('File cannot be opened:') exit() counts = dict() for line in fhand: if line.startswith('From:'):

下面的代码创建一个电子邮件地址字典,以及每封电子邮件出现的频率。以最大频率提取电子邮件的密钥和值的最佳方法是什么

fname = input("Enter file:")
try:
    fhand = open(fname)
except:
    print('File cannot be opened:')
    exit()
counts = dict() 
for line in fhand:  
    if line.startswith('From:'):
         words = line.split(' ', 1)[1]
         words = words.rstrip('\n')

         counts[words] = counts.get(words,0)+1

print(counts)
基于

或者您可以定义两个变量

max_count = 0
frequent = None
并将以下内容附加到if子句中

if counts[words] > max_count
    max_count = counts[words] 
    frequent = words
最后,
frequent
将包含最频繁的电子邮件(如果文件中没有电子邮件,
None

改用,它有一个

或者作为一种理解:

counts = Counter(
    line.rstrip('\n').split(' ', 1)[1]
    for line in fhand
    if line.startswith('From:')
    )

您可以使用

sorted(counts.items(), key=lambda x: x[1])[-1]


您可以反转理解中的键和值,并正常使用max()

count,word = max(c,w for w,c in counts.items())

顺便说一句,顺便说一句,要获得更干净的Python 3代码,请使用
.items()
而不是
.iteritems()
不确定为什么要进行否决。。。这确实有效。感谢您的反馈。
sorted(counts.items(), key=lambda x: x[1])[-1]
sorted(counts.items(), key=lambda x: x[1], reverse=True)[0]
count,word = max(c,w for w,c in counts.items())