From the python documentation I see that dict
has an update(...)
method, but it appears it does not take exceptions where I may not want to update the old dictionary with a new value. For instance, when the value is None
.
从python文档中我看到dict有一个更新(...)方法,但它似乎没有异常,我可能不想用新值更新旧字典。例如,当值为None时。
This is what I currently do:
这就是我目前所做的事情:
for key in new_dict.keys():
new_value = new_dict.get(key)
if new_value: old_dict[key] = new_value
Is there a better way to update the old dictionary using the new dictionary.
有没有更好的方法来使用新词典更新旧词典。
2 个解决方案
#1
11
You could use something like:
你可以使用类似的东西:
old = {1: 'one', 2: 'two'}
new = {1: 'newone', 2: None, 3: 'new'}
old.update( (k,v) for k,v in new.iteritems() if v is not None)
# {1: 'newone', 2: 'two', 3: 'new'}
#2
1
Building on Jon's answer but using set intersection as suggested here:
以Jon的答案为基础,但使用如下所示的集合交集:
In python 3:
在python 3中:
old.update((k, new[k]) for k in old.keys() & new.keys())
In python 2.7:
在python 2.7中:
old.update((k, new[k]) for k in old.viewkeys() & new.viewkeys())
In python 2.7 or 3 using the future
package:
在使用未来包的python 2.7或3中:
from future.utils import viewkeys
old.update((k, new[k]) for k in viewkeys(old) & viewkeys(new))
Or in python 2 or 3 by without the future
package by creating new sets:
或者在python 2或3中通过创建新集合而没有未来的包:
old.update((k, new[k]) for k in set(old.keys()) & set(new.keys()))
#1
11
You could use something like:
你可以使用类似的东西:
old = {1: 'one', 2: 'two'}
new = {1: 'newone', 2: None, 3: 'new'}
old.update( (k,v) for k,v in new.iteritems() if v is not None)
# {1: 'newone', 2: 'two', 3: 'new'}
#2
1
Building on Jon's answer but using set intersection as suggested here:
以Jon的答案为基础,但使用如下所示的集合交集:
In python 3:
在python 3中:
old.update((k, new[k]) for k in old.keys() & new.keys())
In python 2.7:
在python 2.7中:
old.update((k, new[k]) for k in old.viewkeys() & new.viewkeys())
In python 2.7 or 3 using the future
package:
在使用未来包的python 2.7或3中:
from future.utils import viewkeys
old.update((k, new[k]) for k in viewkeys(old) & viewkeys(new))
Or in python 2 or 3 by without the future
package by creating new sets:
或者在python 2或3中通过创建新集合而没有未来的包:
old.update((k, new[k]) for k in set(old.keys()) & set(new.keys()))