Mona Jalal Mona Jalal - 4 months ago 6x
Python Question

syntax_error:update for dictionary

How can I fix this?

# E.g. word_count("I am that I am") gets back a dictionary like:
# {'i': 2, 'am': 2, 'that': 1}
# Lowercase the string to make it easier.
# Using .split() on the sentence will give you a list of words.
# In a for loop of that list, you'll have a word that you can
# check for inclusion in the dict (with "if word in dict"-style syntax).
# Or add it to the dict with something like word_dict[word] = 1.
def word_count(string):
word_list = string.split()
word_dict = {}
for word in word_list:
if word in word_dict:
return word_dict

enter image description here

Disclaimer: A total newbie in Python


To update a key in a dictionary, just assign to the key using [...] subscription syntax:

word_dict[word] = word_dict[word] + 1

or even

word_dict[word] += 1

Your attempt is not valid syntax, for two reasons:

  • word_dict.update() is a method call, everything inside the (...) call syntax must be a valid expression. key: value is not a stand-alone expression, that only is valid within a {key: value} dictionary display. word_dict.update() takes either a dictionary object, or a sequence of (key, value) pairs.
  • word_dict(word) would try to call the dictionary rather than try to retrieve the value for the key word.

Using word_dict.update() to update just one key is a little overkill, because it requires creating another dictionary or sequence. Either one of the following would work:

word_dict.update({word: word_dict[word] + 1})


word_dict.update([(word, word_dict[word] + 1)])

Note that the Python standard library comes with a better solution for counting words: the collections.Counter() class:

from collections import Counter

def word_count(string):
    return Counter(string.split())

A Counter() is a subclass of dict.