oneloop oneloop - 1 year ago 95
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
. I expected this to be allowed though.

Answer Source

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() }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download