Update dictionary with a different dictionary, but only values ​​other than None

From the python documentation, I see what the dictmethod has update(...), but it does not seem to take exceptions where I may not want to update the old dictionary with the new value. For example, when the value None.

This is what I am doing now:

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 an old dictionary with a new dictionary.

+5
source share
2 answers

You can 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'}
+11
source

Based on Jon's answer , but using set intersection as suggested here :

In python 3:

old.update((k, new[k]) for k in old.keys() & new.keys())

In python 2.7:

old.update((k, new[k]) for k in old.viewkeys() & new.viewkeys())

python 2.7 3 future package:

from future.utils import viewkeys
old.update((k, new[k]) for k in viewkeys(old) & viewkeys(new))

python 2 3 future :

old.update((k, new[k]) for k in set(old.keys()) & set(new.keys()))
+1

All Articles