tags:

views:

153

answers:

2

Newbie to Python, so this may seem silly.

I have two dict:

default = {'a': 'alpha', 'b': 'beta', 'g': 'Gamma'}
user = {'a': 'NewAlpha', 'b': None}

I need to update my defaults with the values that exist in user. But only for those that have a value not equal to None. So I need to get back a new dict:

result = {'a': 'NewAlpha', 'b': 'beta', 'g': 'Gamma'}
+6  A: 
result = default.copy()
result.update((k, v) for k, v in user.iteritems() if v is not None)
nosklo
And in Python 3, use user.items()
Ayman
+5  A: 

With the update() method, and some generator expression:

D.update((k, v) for k, v in user.iteritems() if v is not None)
tonfa