I have a list of lists in python full of texts. It is like set words from each document. So for every document i have a list and then on list for all documents.
All the list contains only unique words. My purpose is to count occurrence of each word in the complete document. I am able to do this successfully using the below code:
for x in texts_list:
for l in x:
if l in term_appearance:
term_appearance[l] += 1
else:
term_appearance[l] = 1
But I want to use dictionary comprehension to do the same. This is the first time, I am trying to write dictionary comprehension and using previous existing posts in stackoverflow, I have been able to write the following:
from collections import defaultdict
term_appearance = defaultdict(int)
{{term_appearance[l] : term_appearance[l] + 1 if l else term_appearance[l] : 1 for l in x} for x in texts_list}
Previous post for reference:
Simple syntax error in Python if else dict comprehension
As suggested in above post, I have also used the following code:
{{l : term_appearance[l] + 1 if l else 1 for l in x} for x in texts_list}
The above code was successful in producing empty lists but ultimately threw the following traceback :
[]
[]
[]
[]
Traceback (most recent call last):
File "term_count_fltr.py", line 28, in <module>
{{l : term_appearance[l] + 1 if l else 1 for l in x} for x in texts_list}
File "term_count_fltr.py", line 28, in <setcomp>
{{l : term_appearance[l] + 1 if l else 1 for l in x} for x in texts_list}
TypeError: unhashable type: 'dict'
Any help in improving my current understanding would be much appreciated.
Looking at the above error, I also tried
[{l : term_appearance[l] + 1 if l else 1 for l in x} for x in texts_list]
This ran without any error but the output was empty lists only.