Bottom Page

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)
scidam wrote Aug-06-2019, 12:11 AM:
Please post all code, output and errors (in it's entirety) between their respective tags. I did it for you this time, Here are instructions on how to do it yourself next time.
Quote
#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.
Quote

Top Page

Forum Jump:


Users browsing this thread: 1 Guest(s)