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 (2016, retired 2019) Dictionaries Word Count

Kade Carlson
Kade Carlson
5,928 Points

TypeError: cannot convert dictionary update sequence element #0 to a sequence

Not sure what this means. Any help?

wordcount.py
# E.g. word_count("I do not like it Sam I Am") gets back a dictionary like:
# {'i': 2, 'do': 1, 'it': 1, 'sam': 1, 'like': 1, 'not': 1, 'am': 1}
# Lowercase the string to make it easier.

def word_count(string):
    diction = {}
    words = 1
    for word in string:
        if word.lower() == word.lower():
            words += 1
            diction.update({word.lower(), words})
        else:
            words = 1
            diction.update({word.lower(), words})
    return diction

3 Answers

Stuart Wright
Stuart Wright
41,120 Points

You are getting that error because you are using the wrong syntax for the dictionary update method. It should be:

diction.update({word.lower(): words})

Notice that I replaced the comma with a colon.

Your function still won't pass the challenge as there is something else wrong with it, but you'll get a more helpful error message now and hopefully you can work it out from here. Let me know if you want any more hints though.

Kade Carlson
Kade Carlson
5,928 Points

Bummer! Hmm, didn't get the expected output. Be sure you're lowercasing the string and splitting on all whitespace!

Now it's giving me this error lol

Kade Carlson
Kade Carlson
5,928 Points

I tried the split method but it still didn't work

Stuart Wright
Stuart Wright
41,120 Points

You can get a list of all lowercased words in the string using this:

list_of_words = string.lower().split()

Once you've got this list of words to work with, it should be easier to create the word count dictionary. Your original code was looping over the string, which means it is checking one character at a time rather than one word at a time.

This should do the trick

def word_count(arg):
    words = arg.lower().split()
    keys = set(words)
    ret = dict(zip(keys, [0 for  _ in range(len(keys))]))
    for key in words:
        if ret.get(key) is not None:
            ret[key] += 1
    return ret