当更新依赖于字典值本身时,是否有python方法来更新字典值?

2024-10-01 00:17:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我发现自己在很多情况下都有一个字典值,我想用一个新值更新它,但前提是新值满足与当前值相关的一些条件(例如更大)。在

目前我写的表达式类似于:

dictionary[key] = max(newvalue, dictionary[key])

这很好,但我一直在想,也许有一种更简洁的方法,不需要重复我自己。在

谢谢你的建议。在


Tags: 方法keydictionary字典表达式情况条件建议
3条回答

不确定它是否“更整洁”,但避免重复的一种方法是使用面向对象的方法,并将内置的dict类的子类化,使某些东西能够做你想做的事情。这还有一个优点,即可以使用自定义类的实例来代替dict实例,而无需更改其余代码。在

class CmpValDict(dict):
    """ dict subclass that stores values associated with each key based
       on the return value of a function which allow the value passed to be
       first compared to any already there (if there is no pre-existing
       value, the second argument passed to the function will be None)
    """
    def __init__(self, cmp=None, *args, **kwargs):
        self.cmp = cmp if cmp else lambda nv,cv: nv  # default returns new value
        super(CmpValDict, self).__init__(*args, **kwargs)

    def __setitem__(self, key, value):
        super(CmpValDict, self).__setitem__(key, self.cmp(value, self.get(key)))

cvdict = CmpValDict(cmp=max)

cvdict['a'] = 43
cvdict['a'] = 17
print cvdict['a']  # 43

cvdict[43] = 'George Bush'
cvdict[43] = 'Al Gore'
print cvdict[43]  # George Bush

只需为自己编写一个helper函数:

def update(dictionary, key, newvalue, func=max):
    dictionary[key] = func(dictionary[key], newvalue)

您可以使用封装该逻辑的update方法使values成为对象。或子类dictionary并修改__setitem__的行为。请记住,您这样做会使不熟悉您的代码的人不太清楚发生了什么。你现在所做的是非常明确和明确的。在

相关问题 更多 >