2013-12-09 124 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")