I want to count the number of times a word occurred in a paragraph, say I have 2D list.
If I write below dict comprehension somehow it doesn't work but the nested for loops does the job. What is the difference and why the comprehension not working?
EXAMPLE:
If I write below dict comprehension somehow it doesn't work but the nested for loops does the job. What is the difference and why the comprehension not working?
EXAMPLE:
sentences = ["a new world record was set", "in the holy city of ayodhya", "on the eve of diwali on tuesday", "with over three lakh diya or earthen lamps", "lit up of simultaneously on the banks of the sarayu river"] d=dict() d = { word: (d.get(word, 0) + 1) for line in sentences for word in line.split(" ") } ## says all the word occurred only once ##But below nested for does perfect job for line in sentences: for word in line.split(' '): d[word] = d.get(word,0) + 1 print(d)