Help
cancel
Showing results for 
Search instead for 
Did you mean: 
Pilot Lvl 1
Message 1 of 4

Dictionaries questions

Hey everyone

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
dictionary."

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.

Thanks!

3 Replies
Pilot Lvl 3
Message 2 of 4

Re: Dictionaries questions

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? 

 

 

Pilot Lvl 1
Message 3 of 4

Re: Dictionaries questions

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!

Community Manager
Message 4 of 4

Re: Dictionaries questions

Hi @Maaazi,

 

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.

 

Cheers!

Mark helpful posts with Accept as Solution to help other users locate important info. Don't forget to give Kudos for great content!