I am pretty new to Python and to help new learn, I am building a program, which I want broken down into 2 steps:
Step 1) Count the number of a particular words in a text file, store that in a dictionary where the key, value pairs are {word, count}
Step 2) Order the dictionary from (1) in descending order, to show the top 100 words
Step 1 works fine but in attempting step 2, I am struggling to call the dictionary from the first function. I create a new variable 'tallies' but this is a tuple and shows only the first entry in the dictionary.
How do I call the full dictionary to my 2nd function?
Thanks.
filename = 'nameoffile.txt'
def tally():
file = open(filename,'r')
wordcount={}
for word in file.read().split():
if word not in wordcount:
wordcount[word] = 1
else:
wordcount[word] += 1
for k,v in wordcount.items():
return k,v
def Count():
tallies = tally()
print tallies
Count()