I am trying to get a for loop to compare 2 values edit it accordingly, but it is not working

Viewed 28
# 1st loop iterates through user sentence list
for value in user_sentence:
    # iterates through words_dict dictionary, the key is compared and the value is what replace value
    for i in words_dict:  
        if value == i:
            value = words_dict[i]
print(user_sentence[1])

I do not understand why the nested for loop is not working, when I change user_sentence[1] directly it works, but when I put it in the nested loop it does not work. What am I doing wrong?

1 Answers

Because you are assigning it to value variable, not to the list item. You can iterate through the index, and value of the user_sentence list using enumerate, then modify the value at current index if value equals i.

# 1st loop iterates through user sentence list
for idx,value in enumerate(user_sentence):
    # iterates through words_dict dictionary, the key is compared and the value is what replace value
    for i in words_dict:  
        if value == i:
            user_sentence[idx] = words_dict[i]
            #break
print(user_sentence[1])

On a side note, you can break the inner loop which I've commented in above code snippet. It'll just exit the inner loop after finding the first match, this way, you don't need to run loop for all the dictionary items.

Related