在python中是否有另一种方法可以从除del key [value]之外的字典中删除键值对?

时间:2016-06-27 09:32:23

标签: python dictionary

我有一个单独工作的函数,但是当我尝试在另一个函数中使用它时会引发一个关键错误。而不是试图解释更大的上下文,我认为只更改 del hand [letter] 会更容易,这是引发错误的地方。在某些情况下,我可以将hand [letter]改为hand.get(letter,None),但我不能将它与del运算符一起使用,它会抛出错误。有什么想法吗?

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

2 个答案:

答案 0 :(得分:5)

使用.pop,因此如果密钥不存在,则在使用默认值时不会抛出任何错误,例如None

hand.pop(letter, None)
#                  ^ pops None when the key letter does not exist

由于您已经检查过if个条件中是否存在相同的密钥,因此您可以执行以下操作:

for letter in letters:
    if letter in hand: # same as letter in hand.keys()
         hand[letter] = hand[letter] - 1
         if hand[letter] <= 0:
             hand.pop(letter, None) # del hand[letter] should not throw errors in this case

答案 1 :(得分:0)

如果你的功能“在它自己的情况下工作正常但在从另一个函数调用时会提升”,那么首先要做的就是找出为什么你在第二种情况下遇到问题。另外,这是programming by accident的典型例子 - 我们都知道这种做法从长远来看是不可行的。

现在函数代码中有KeyError的明显原因,它不依赖于函数输入的任何其他内容:您尝试删除密钥而不先检查它是否存在({{1}声明)。尝试为if hand[letter] <= 0: param传递一个空字典,你会发现你的函数“就可以自行运行”。

相关问题