简体   繁体   中英

how can i change keys with values in python?

I want to take words from the user in such a way that the user has to enter the word and write the translation in front of it and with a space, then write his sentence, if his words are in the dictionary, replace those words with his translation but i dont know how can i change them? for example: -enter numbers of you're words to translate: -enter you're words: say decir -we Nosotros -goodnight buenasnoches -you usted -tonight esta noche -enter you're sentence:we say goodnight to you tonight -i want output like this:nosotros decir buenasnoches to usted esta noche


list1=[]
list2=[]
list3=[]
numbersofwords=int(input('enter numbers of you're words to translate: '))
for i in range(words):
    words=list(input('enter you're words: ').split())
    list1.append(words)
for x in range(len(list1)):
    list2.append(list1[x][1])
    list3.append(list1[x][0])    
    translator1=tuple(list2)
    translator2=tuple(list3)
translator=dict(zip(translator2, translator1))
finalsentence=input('enter you're sentence: ')

you can create a new dict entry and delete the old one:

dictionary[new_key] = dictionary[old_key]
del dictionary[old_key]

or in one line like this:

dictionary[new_key] = dictionary.pop(old_key)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM