0

The following code creates a dictionary of email addresses and how frequently each email appears. What is the best way to pull out the key and value for the email with the max frequency?

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)
wjandrea
  • 28,235
  • 9
  • 60
  • 81

4 Answers4

0

Based on Getting key with maximum value in dictionary?

import operator
max(counts.iteritems(), key=operator.itemgetter(1))[0]

Or you can define two variables

max_count = 0
frequent = None

and append the following to the if clause

if counts[words] > max_count
    max_count = counts[words] 
    frequent = words

At the end frequent would contain most frequent email (or None if there is no email in file).

Serge
  • 3,387
  • 3
  • 16
  • 34
0

you can get both the key and value using

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

or

sorted(counts.items(), key=lambda x: x[1], reverse=True)[0]
kait
  • 1,327
  • 9
  • 13
0

You can invert the key and value in a comprehension and use max() normally:

count,word = max(c,w for w,c in counts.items())
Alain T.
  • 40,517
  • 4
  • 31
  • 51
-1

Use collections.Counter instead, which has a most_common method.

from collections import Counter

# Ignoring file opening code since it's irrelevant...

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

print(counts.most_common(1))

Or as a comprehension:

counts = Counter(
    line.rstrip('\n').split(' ', 1)[1]
    for line in fhand
    if line.startswith('From:')
    )
wjandrea
  • 28,235
  • 9
  • 60
  • 81