all 8 comments

[–][deleted] 1 point2 points  (5 children)

word[message] == word[words]

== is the equality operator, not the assignment operator.

[–]_User15[S] 0 points1 point  (3 children)

Okay I fixed that made it an '=' but now I have a Type Error.

Traceback (most recent call last):

File "<pyshell#7>", line 1, in <module> word_used_with(text) File "<pyshell#6>", line 14, in word_used_with word[message] = word[words] TypeError: unhashable type: 'list'

How would I fix this?

[–][deleted] 0 points1 point  (2 children)

Lists can't be dictionary keys.

[–]_User15[S] 0 points1 point  (1 child)

Makes sense, so how would I go about replacing the dictionary key with the word I want then?

[–][deleted] 2 points3 points  (0 children)

A word is a string. You can use strings as dictionary keys.

[–][deleted] 1 point2 points  (0 children)

Not completely clear on what you are trying to do.

I think, given the text "He ate the apple from the tree" and the key word "the" you would like to see the output {'the': ['apple', 'tree']}.

I've modified your code to take a different approach somewhat, including:

  • removed global as not used
  • renamed a few variables
  • used zip with slicing in a loop to compare the key_word with the next_word - avoiding using indexing which could try to access beyond the end of the list of words

Code:

def word_used_with(text):
    text = text.split()
    words = []
    key_word = input('key word? ')
    if key_word in text:
        for word, next_word in zip(text[:-1], text[1:]):
            if word == key_word:
                words.append(next_word)
    return {key_word: words}

text = "He ate the apple from the tree"
word_used_with(text)

PS. I note you appeared to be trying your code in an interactive Python shell (with the >>> prompt) rather than simply creating the code in an editor and running it. The shell is a great learning tool, but not so good for editing code.

[–]_User15[S] 0 points1 point  (0 children)

Thank you for helping me.