Trying to modify list output using Python 3

Viewed 31

Im trying to write a program to take in a file input, read the file and save the contents to a list. Then it counts each word and prints the top 'n' number of words which in my example is 10.

When I print the final value it prints

('the', 31) ('of', 24) ('to', 16) ('we', 16) ('and', 13) ('a', 12) ('our', 10) ('that', 8)('not', 7) ('in', 7)

Im trying to achieve the output of

{ the : 31 , of : 24, to : 16 , and : 13, a : 12 , our : 10 , that : 8, not : 7, in : 7}

Currently my code is:

mostFrequent = [] #list to hold the contents
fileName = input("Enter a file name: ")
with open(fileName, "r") as i: #while file is open read each line and add it to the list
  for line in i:
    mostFrequent.extend(line.split())

wordCounter = Counter(mostFrequent) #counts each word in the list
topMostFrequent = wordCounter.most_common(10) #gets top 10 most common words
print(*topMostFrequent, sep='\n') #printing list without [] and putting each value on new line

I tried converting the list to a dictionary since it seems the dictionary would produce the output I wanted but I couldn't get it to work, any help would be excellent!

1 Answers
dict(topMostFrequent)
topMostFrequent = [('the', 31), ('of', 24), ('to', 16), ('we', 16), ('and', 13), ('a', 12), ('our', 10) ,('that', 8),('not', 7), ('in', 7)]
topMostFrequent = {i[0]:i[1] for i in topMostFrequent }
topMostFrequent
topMostFrequent = [('the', 31), ('of', 24), ('to', 16), ('we', 16), ('and', 13), ('a', 12), ('our', 10) ,('that', 8),('not', 7), ('in', 7)]
topMostFrequent = dict(map(lambda x: [x[0],x[1]], topMostFrequent))
# or dict(map(lambda x: x, topMostFrequent))
topMostFrequent

Output:

{'the': 31,
 'of': 24,
 'to': 16,
 'we': 16,
 'and': 13,
 'a': 12,
 'our': 10,
 'that': 8,
 'not': 7,
 'in': 7}
Related