1

I am trying the below piece of code where I am trying to read the contents of a file and identify the 3 most used words. I have the individual words and their frequencies as a key:value in a python dict. When I try to use the sorted() on it, I get 'list' object not callable error.

content=open("Assignment1_Q8.txt").read().split()
freq={}
for item in content:
    if item in freq:
        freq[item]+=1
    else:
        freq[item]=1
    
print(freq)

freq_sort=sorted(freq,key=freq.values())

Output:
{'Hello': 5, 'World': 3, 'Hi': 3, 'Bye': 5}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-220-40658aa1ff31> in <module>
      8 print(freq)
      9 
---> 10 freq_sort=sorted(freq,key=freq.values())

TypeError: 'list' object is not callable

vijayt
  • 11
  • 2

2 Answers2

0

Read the documentation of sorted(iterable, key=key, reverse=reverse). key is a function to execute to decide the order. You use list as key so it throws an error.

How do I sort a dictionary by value? You may use this as a reference for what you wanted.

0

Issue was that I had used 'sorted' earlier as a variable and I was trying to use it as a function later. I deleted the 'sorted' variable annd executed the code and it works. Thanks.

vijayt
  • 11
  • 2