Casey Casey - 1 month ago 22
Python Question

Dictionary comprehension set value to None

I need to loop through every value in a dictionary and replace '' with None. What am I doing wrong?

data = {'phone': '', 'email': 'joe@hotmail.com', 'fname': 'Joe', 'zip_code': '', 'address2': '', 'address1': '', 'city': '', 'state': '', 'lname': 'Yang'}

clean = {k: v=None for k, v in data.items() if v == ''}


Result

clean = {k: v=None for k, v in data.items() if v == ''}
^
SyntaxError: invalid syntax

Answer

You want to use shorthand-if as a value expression, not comprehension conditional (which will in fact remove key entirely).

data = {'phone': '', 'email': 'joe@hotmail.com', 'fname': 'Joe', 'zip_code': '', 'address2': '', 'address1': '', 'city': '', 'state': '', 'lname': 'Yang'}
clean = {k: None if v == '' else v for k, v in data.items()}