Search code examples
pythoncountingitems

Why do the use of > in this code produce an error?


Trying to use the .get function in a dictionary.

I have not tried much, as I do not know that much yet.

name = input("Enter file: ")
handle = open(name)
counts = dict()
for line in handle:
    words = line.split()
    for word in words:
        counts[word] = counts.get(word, 0) + 1

bigcount = None
bigword = None
for word, count in counts.items():
    if bigcount is None or count > bigcount:
        bigcount = word
        bigword = count

I get this result:

 if bigcount is None or count > bigcount:
TypeError: '>' not supported between instances of 'int' and 'str'

What it should produce is a number. What is wrong?


Solution

  • If you use collections.Counter instead of re-implementing it, you won't have the opportunity to make such an error.

    from collections import Counter
    
    
    counts = Counter()
    name = input("Enter file: ")
    with open(name) as handle:
        for line in handle:
            counts.update(line.split())
    
    bigword, bigcount = counts.most_common(1)[0]