Why is it giving me this list comprehension error

sentence = "What is the Airspeed Velocity of an Unladen Swallow?"
# Don't change code above ๐Ÿ‘†

# Write your code below:

dict1 = {new_key:newword for item in sentence.split()}


Traceback (most recent call last):
  File "main.py", line 7, in <module>
    dict1 = {new_key:newword for item in sentence.split()}
  File "main.py", line 7, in <dictcomp>
    dict1 = {new_key:newword for item in sentence.split()}
NameError: name 'new_key' is not defined

Neither new_key or newword are defined variables in this code. When the interpreter hits a variable that isnโ€™t defined it will throw this error. new_key just happens to be the first undefined variable it runs into here.
In each loop of the comprehension, item will become a word in the sentence, but there isnโ€™t anything here initializing those other two variables, nor is item used in the comprehension. You will need to establish what the dictionary keys and values are going to be. One possibility (as I donโ€™t actually know what the goal here is), is to use the enumerate() function to generate an index along with each item or make a custom list of keys and use zip() to pair them together.

dict1 = dict(enumerate(sentence.split()))

If its not already late, this should helpโ€ฆ

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.