Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

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.

like image 516
Vaibhav Bajpai Avatar asked Mar 07 '13 17:03

Vaibhav Bajpai


1 Answers

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'}
like image 155
Jon Clements Avatar answered Oct 19 '22 10:10

Jon Clements