oneloop oneloop - 3 months ago 10
Python Question

Why is this SyntaxError? (Python, dictionary comprehension with inline if)

In a dictionary, I want to make sure that a specific key has a specific encoding.

test_dictionary = { k:v.encode('latin-1') if k=="test_key" else k:v for k,v in test_dictionary.items() }


I get
SyntaxError
. I expected this to be allowed though.

Answer

Try this instead:

test_dictionary = { k:v.encode('latin-1') if k=="test_key" else v for k,v in test_dictionary.items() }

The second : has been removed so the inline if either encodes v, or leaves it as it is depending on the condition.

To clarify I've added parentheses to the expression below to make it clearer that this is the "value" part of the list comprehension:

{ k: (v.encode('latin-1') if k=="test_key" else v) for k,v in test_dictionary.items() }
     ^___________________________________________^