我有一個函數可以正常工作,但當我嘗試在另一個函數中使用它時引發了一個關鍵錯誤。我認爲只是改變德爾手[字母],這是錯誤發生的地方,而不是試圖解釋更大的上下文。在某些情況下,我可以將hand [letter]改爲hand.get(letter,None),但是我不能在del運算符中使用它,它會引發錯誤。有任何想法嗎?Python中有另一種方法可以從除del [key]以外的字典中刪除鍵值對嗎?
hand = {'r': 2, 'a': 3, 'p': 2, 'e': 1, 't': 1, 'u':1}
word = 'rapture'
def update_hand(hand, word):
"""This function loops through letters, and if the letter is in the \
hand, it reduces the corresponding int value by one, until there is \
no longer that letter in the hand, then it deletes the key,value pair \
all together"""
letters = set(word)
for letter in letters:
if letter in hand.keys():
hand[letter] = hand[letter]-1
if hand[letter] <= 0:
del hand[letter]
return hand
嘗試'pop'字典成員函數 – jmetz