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)的结果所示
不,但您可以继承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不检查是否存在"真实"更改; 它只是注意到有一个变化.
我喜欢以下解决方案:
>>> 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'}