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.
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'}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With