Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Python Collections (Retired) Dictionaries Unpacking Dictionaries

dongji cui
dongji cui
2,464 Points

Questions of if.. in syntax in python

def word_count(a_string):
  string_dict = {}
  for word in a_string.split():
    if word in string_dict:  # can anyone explain code in this line. I am totally confused, because there is nothing in string_dict. How can we use if... in to determine ?
        string_dict[word] += 1
    else:
        string_dict[word] = 1
  return string_dict

a_string = "I am what i am because of God"
a_string = a_string.lower()
print(word_count(a_string))

Hi dongji cui, I've formatted your code to make it easier to read. Also, just note that comments in Python use the hash/pound symbol: #

1 Answer

Hi dongji cui, you're correct, it is checking if the word already exists in string_dict as a key.

The reason it is done this way is because if you try and change the value of a dict key that doesn't exist, you will get a KeyError. This if/else statement checks to make sure it exists and if it doesn't, it will create it.

If it does, it will increase the value by 1 (that is, it will increment the counter value for that word).

If not, it will add the word to string_dict as the key, and make the value equal 1 to indicate the word has appeared once.

It will continue on for each word in the string until it finishes.