python dict更新差异

时间:2009-04-03 19:04:34

标签: python diff dictionary

python是否具有任何内置功能,可以通知在dict更新时更改了哪些字典元素?例如,我正在寻找这样的功能:

>>> 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'}

我希望获得更改值的字典,如a.diff(b)的结果所示

6 个答案:

答案 0 :(得分:10)

不,但您可以继承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 )

请注意,此处定义的超类Watcher不检查是否存在“真实”更改;它只是注意到有一个变化。

答案 1 :(得分:9)

一年后

我喜欢以下解决方案:

>>> 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'}

答案 2 :(得分:2)

不,它没有。但是编写字典差异函数并不难:

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

答案 3 :(得分:2)

简单的差异化功能很容易编写。根据您需要的频率,它可能比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 })

答案 4 :(得分:1)

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'}

答案 5 :(得分:0)

没有内置,但你可以迭代dict的键并进行比较。可能会很慢。

更好的解决方案可能是构建更复杂的数据结构并使用字典作为底层表示。