0

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
Casey
  • 2,093
  • 5
  • 25
  • 43

2 Answers2

3

You can't do an assignment in a dictionary comprehension.

What you want is a ternary operator that replaces empty string values with None and returns others as is:

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

Reference:

Does Python have a ternary conditional operator?

Community
  • 1
  • 1
Moses Koledoye
  • 71,737
  • 8
  • 101
  • 114
2

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()}
Łukasz Rogalski
  • 18,883
  • 6
  • 53
  • 84