Python Forum
Dictionary comprehension Question
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dictionary comprehension Question
#1
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:

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)
Reply
#2
You can't reference the object before it's created.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020