2013-12-09 126 views
0

您好,我正在构建一个小项目,用户可以在字典中输入新的键和值。如果用户输入已经输入字典的键或值,告诉他们需要输入新键或值,因为他们当前输入的键已经存在,是否可以显示信息?在Python中更新字典

这是我目前使用的一些代码。

# dictionary with key:values. 
reps = {'#':'A', '*':'M', '%':'N'} 

### The users guess 

print ("Now it's your turn to guess the rest of the letters!") 

###Score 
guesses = 0 

### Update the dictionary with the users new guesses 
while guesses < 10: 
    symbol = input('Please enter the symbol: ') 
    letter = input('Please enter the letter: ') 
    reps[symbol] = letter 

### Re printing the updated list 
    for line in lines_words: 
     txt = replace_all(line, reps) 
     print (txt) 
    guesses + 1 
+0

如果代码中的符号或reps.values()中的字母应该 – user2390183

回答

1

可以测试现有的密钥和值in

if symbol in reps: 
    print("You already defined that symbol") 

对于字母,你必须在字典中,以测试对所有值

if letter in reps.values(): 
    print("You already defined that letter") 

你可以将两者结合起来:

if symbol in reps or letter in reps.values(): 
    print("You already used either the symbol or the letter")