开发者

Getting keys that were updated with the using a dictionaries update method

开发者 https://www.devze.com 2023-03-21 19:18 出处:网络
Is it possible to get the keys that where changed when using the update method? def func(**kw): d = {\'key0\' : 0, \'key1\' : 1}

Is it possible to get the keys that where changed when using the update method?

def func(**kw):
    d = {'key0' : 0, 'key1' : 1}
    d.update(**kw)

func(kw0=0, kw1=1)

In the above code I'd want to get the key开发者_运维问答s 'kw0' and 'kw1'.


No, once update() is called, they are indistinguishable from the other keys.

Inside the function you can still look at kw.keys() to see which ones were passed in

eg

def func(**kw):
    d = {'key0' : 0, 'key1' : 1}
    d.update(**kw)
    print "updated %s"%kw.keys()

func(kw0=0, kw1=1)


The only way to detect the keys that were changed, is to store a copy of original dict, and then compare updated version, and original version.

def func(**kw):
    d = {'key0' : 0, 'key1' : 1}
    old = dict(d)
    d.update(kw)
    changed_keys = [key for key in d if old.get(key) != d.get(key)]
    print changed_keys
0

精彩评论

暂无评论...
验证码 换一张
取 消