Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete None values from Python dict

Tags:

python

Newbie to Python, so this may seem silly.

I have two dicts:

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'}
like image 766
Ayman Avatar asked Aug 26 '09 11:08

Ayman


2 Answers

result = default.copy()
result.update((k, v) for k, v in user.iteritems() if v is not None)
like image 193
nosklo Avatar answered Sep 28 '22 08:09

nosklo


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

D.update((k, v) for k, v in user.iteritems() if v is not None)
like image 37
tonfa Avatar answered Sep 28 '22 08:09

tonfa