English 中文(简体)
当更新取决于值本身时,是否有音波方式更新字典值?
原标题:Is there a pythonic way to update a dictionary value when the update is dependent on the value itself?
  • 时间:2012-05-25 15:56:00
  •  标签:
  • python

我发现自己身处许多情况中, 我有一个字典价值, 我想用新的价值来更新, 但只有当新价值符合与当前价值(如更大)相关的某些标准时,

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

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

但我一直认为 做这件事的方法可能更干净 不需要重复

谢谢你的建议

最佳回答

给自己写一个帮手函数:

def update(dictionary, key, newvalue, func=max):
    dictionary[key] = func(dictionary[key], newvalue)
问题回答

您可以使用包含逻辑的更新方法来设定值对象。 或者子类字典, 并修改 > 的行为 。 记住, 任何这样的做法都会让不熟悉您的代码的人更不清楚地知道正在发生什么。 您现在正在做的是最清晰明了的。

不知道它是否是“neater”,但避免重复自己的方法之一是使用一个面向对象的方法和子分类 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

如何使用 Python 版本的永久操作员 :

d[key]=newval if newval>d[key] else d[key]

或一条线,如果:

if newval>d[key]: d[key]=newval




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签