Update a dictionary with another dictionary, but only non-None values

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.items() if v is not None)

# {1: 'newone', 2: 'two', 3: 'new'}

Update: I think I was trying to answer the wrong question here (see my comment below), since this clearly does not answer the question being asked. In case there is something useful, I'll leave this here anyway (unless someone makes it clear that it would be better to just delete it).

Building 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())

In python 2.7 or 3 using the future package:

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:

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

Tags:

Python