Home>

I ran into the problem that when certain characters are found in array, the program simply ignores the same second element, and in output shows what was in input.

For example, here's my code:

list= str (input ()). split ()
dict= {"X-(": "Angry",
        "<
/3 ":" Broken Heart ",
        ": _ (": "Crying",
        ": *)": "Drunk",
        "| -O": "Yawn",
        ";)": "Winking",
        ": -) *": "Kiss",
        ";-)": "Winking",
        ": S": "Sarcastic",
        ":-(": "Sad",
        "XD": "Laughing",
        ":)": "Happy",
        ":-)": "Happy",
        ": -*": "Kiss",
        ":-P": "Frustrated"}
for key, value in dict.items ():
    if key in list:
        b= list.index (key)
        list [b]= value
    else:
        pass
print ('' .join (list))

In this code, the user enters text in the form of emoticons, and the program will give him emoticons translated into text.

If you enter this text: I like you so much How its going :-P :-P

Then it will output: I like you so much How its going Frustrated :-P

This is the problem, that when it sees the second such character in input, it ignores it and leaves it the same.

  • Answer # 1

    In general, this is all much shorter (I re-called the variables so that there is no intersection with the built-in python types):

    print ('' .join (dict_.get (w, w) for w in list_))
    

    Just iterate over the words and replace them in the dictionary. Where he does not find a word in the dictionary, he leaves the original one. For this, the second parameter of the method is used..getdictionary, it says what the dictionary should return if there is no such key.

  • Answer # 2

    In general, this is all much shorter (I re-called the variables so that there is no intersection with the built-in python types):

    print ('' .join (dict_.get (w, w) for w in list_))
    

    Just iterate over the words and replace them in the dictionary. Where he does not find a word in the dictionary, he leaves the original one. For this, the second parameter of the method is used..getdictionary, it says what the dictionary should return if there is no such key.

  • Answer # 3

    Replace

    if key in list:
    

    on

    while key in list:
    

    And yes, don't name variableslist,dictetc. (by the names of built-in types /functions) Sooner or later, you yourself will step on your own mistake.