简体   繁体   中英

'list' object not callable error while using sorted() in Python on Jupyter notebook

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM