I've recently started learning how to code with Python and I'm using the "Python for everybody" book, I have a problem with an exercise in chapter 9 :
"Write a program that reads the words in words.txt and stores them as
keys in a dictionary. It doesn’t matter what the values are. Then you
can use the in operator as a fast way to check whether a string is in the
So,what I came up with is this code :
w = dict() file = open("words.txt") for line in file : words = line.split() for word in words : if word not in w : w[word] = 1 else : w[word] = w[word] + 1 print(w)
I was wondering if there's a more efficient way to do or I can make it better.
Your implementation is "correct" but it can be simplified a little for the goal stated.
Your code is actually counting the number of times a word appears in 'words.txt'. Since the goal is to only see if words in a string are in the dictionary, the counting is overkill.
If a key already exists in the dictionary, the value is updated. So if counting isn't done, the check for the key already in the dictionary is unnecessary.
Some good info here - you might be able to do w.update(words) without looping?
Hi and thanks for you reply!
I've checked the link you posted but the thing is that it works by creating a dictionary of some words. My issue is that I already have the text and want to add it's words to a dictionary. I came up with another solution and instead of checking if a word is in the dictionary, I just gave them a value of 0, so it looks something like this
for word in words : counts[word] = 0
thanks once again for your help!
This post was moved to a different board that fits your topic of discussion a bit better. This means you’ll get better engagement on your post, and it keeps our community organized so users can more easily find information.
As you’ll notice, your topic is now here in the Programming Help board. No action is needed on your part; you can continue the conversation as normal here.
Mark helpful posts with Accept as Solution to help other users locate important info. Don't forget to give Kudos for great content!