我所有的键都使用相同的值

时间:2018-08-29 14:22:18

标签: python python-2.7

我的代码有问题!我正在制作一个程序,该程序将创建一个文件,该文件将使用字典在您的定义旁边存储单词。到目前为止,我已经按照预期的方式工作了,但是当我看到结果时,每个返回的键都具有相同的值。为什么/

words = {}

word = raw_input("What word is it? ")
definition = raw_input("What's the meaning of the word ")
words[word] = definition

addition = raw_input('Have another word you need to remember? Y/N ')

while addition == "Y":
    word = raw_input("What word is it? ")
    definition = raw_input("What's the meaning of the word ")
    words[word] = definition
    addition = raw_input('Have another word you need to rememeber? Y/N ')

# How to get my key to display the correct information.

for key, value in words.items():
    print(key + ": " + definition)


f = open("Dcitionary.txt", "w")

for key, value in words.items():
    f.write(key + ": " + definition)

f.close

1 个答案:

答案 0 :(得分:-1)

这里有一些改进,但是如果您两次引入相同的单词,它将覆盖现有单词:

dictionary_words={}

addition="Y"
while addition=="Y":
    word = raw_input("What word is it? ")
    definition = raw_input("What's the meaning of the word ")
    dictionary_words[word]=definition
    addition = raw_input('Have another word you need to rememeber? Y/N ')

print ("\n\n Key-Values\n")
for i in dictionary_words:
    print (i+" : "+dictionary_words[i])

您应该对该代码进行很多改进,条件是在这种情况下,对于任何与“ Y”不同的字符都停止;那么您也应该提高拥有多个值的键的机会。 但这是一个很小的改进,而且可以打印

  

键:值