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)的结果所示
发布于 2009-04-03 11:23:18
不能,但您可以子类化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不会检查是否有“真正的”更改;它只是说明有更改。
发布于 2010-05-25 12:02:04
一年后
我喜欢以下解决方案:
>>> 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'}
发布于 2009-04-03 11:13:36
不,不需要。但是编写一个字典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
https://stackoverflow.com/questions/715234
复制相似问题