简体   繁体   English

python dict更新差异

[英]python dict update diff

Does python have any sort of built in functionality of notifying what dictionary elements changed upon dict update? python是否具有任何内置功能,可以通知在dict更新时更改了哪些字典元素? For example I am looking for some functionality like this: 例如,我正在寻找这样的功能:

>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> a.diff(b)
{'c':'pepsi', 'd':'ice cream'}
>>> a.update(b)
>>> a
{'a':'hamburger', 'b':'fries', 'c':'pepsi', 'd':'ice cream'}

I am looking to get a dictionary of the changed values as shown in the result of a.diff(b) 我希望得到一个更改值的字典,如a.diff(b)的结果所示

No, but you can subclass dict to provide notification on change. 不,但您可以继承dict以提供有关更改的通知。

class ObservableDict( dict ):
    def __init__( self, *args, **kw ):
        self.observers= []
        super( ObservableDict, self ).__init__( *args, **kw )
    def observe( self, observer ):
        self.observers.append( observer )
    def __setitem__( self, key, value ):
        for o in self.observers:
            o.notify( self, key, self[key], value )
        super( ObservableDict, self ).__setitem__( key, value )
    def update( self, anotherDict ):
        for k in anotherDict:
            self[k]= anotherDict[k]

class Watcher( object ):
    def notify( self, observable, key, old, new ):
        print "Change to ", observable, "at", key

w= Watcher()
a= ObservableDict( {'a':'hamburger', 'b':'fries', 'c':'coke'} )
a.observe( w )
b = {'b':'fries', 'c':'pepsi'}
a.update( b )

Note that the superclass Watcher defined here doesn't check to see if there was a "real" change or not; 请注意,此处定义的超类Watcher不检查是否存在“真实”更改; it simply notes that there was a change. 它只是注意到有一个变化。

one year later 一年之后

I like the following solution: 我喜欢以下解决方案:

>>> def dictdiff(d1, d2):                                              
        return dict(set(d2.iteritems()) - set(d1.iteritems()))
... 
>>> a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
>>> b = {'b':'fries', 'c':'pepsi', 'd':'ice cream'}
>>> dictdiff(a, b)
{'c': 'pepsi', 'd': 'ice cream'}

No, it doesn't. 不,它没有。 But it's not hard to write a dictionary diff function: 但是编写字典diff函数并不难:

def diff(a, b):
  diff = {}
  for key in b.keys():
    if (not a.has_key(key)) or (a.has_key(key) and a[key] != b[key]):
      diff[key] = b[key]
  return diff

A simple diffing function is easy to write. 简单的差异功能很容易编写。 Depending on how often you need it, it may be faster than the more elegant ObservableDict by S.Lott. 根据您需要它的频率,它可能比S.Lott更优雅的ObservableDict更快。

def dict_diff(a, b):
    """Return differences from dictionaries a to b.

    Return a tuple of three dicts: (removed, added, changed).
    'removed' has all keys and values removed from a. 'added' has
    all keys and values that were added to b. 'changed' has all
    keys and their values in b that are different from the corresponding
    key in a.

    """

    removed = dict()
    added = dict()
    changed = dict()

    for key, value in a.iteritems():
        if key not in b:
            removed[key] = value
        elif b[key] != value:
            changed[key] = b[key]
    for key, value in b.iteritems():
        if key not in a:
            added[key] = value
    return removed, added, changed

if __name__ == "__main__":
    print dict_diff({'foo': 1, 'bar': 2, 'yo': 4 }, 
                    {'foo': 0, 'foobar': 3, 'yo': 4 })
def diff_update(dict_to_update, updater):
    changes=dict((k,updater[k]) for k in filter(lambda k:(k not in dict_to_update or updater[k] != dict_to_update[k]), updater.iterkeys()))
    dict_to_update.update(updater)
    return changes

a = {'a':'hamburger', 'b':'fries', 'c':'coke'}
b = {'b':'fries', 'c':'pepsi'}
>>> print diff_update(a, b)
{'c': 'pepsi'}
>>> print a
{'a': 'hamburger', 'c': 'pepsi', 'b': 'fries'}

Not built in, but you could iterate on the keys of the dict and do comparisons. 不是内置的,但你可以迭代字典的键并进行比较。 Could be slow though. 可能会很慢。

Better solution is probably to build a more complex datastructure and use a dictionary as the underlying representation. 更好的解决方案可能是构建更复杂的数据结构并使用字典作为底层表示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM