Quentin Quentin - 1 month ago 5
Python Question

Dictionary comprehension with if and else statement in Python

I would like to make a dictionary comprehension with

if
and
else
statement but I get a
SyntaxError
.

Here is what I have

my_variable = {}
list_A = [c, d, e]
list_B = [a, b, c]


And here is wat I want to do

my_variable = {
x:[7.0]
if x in list_A
else x:[0.0]
for x in list_B}


Unfortunately, I get a
SyntaxError
on the
else x:[0.0]
part, and I don't understand how to do it differently keeping the dictionary comprehension system.

Any idea how to make it work?

Answer

The key and value parts of a {key: value for ... in ...} dict comprehension are separate expressions. You only want to vary the value expression here, so use ... if ... else ... for that part only:

my_variable = {
    x: [7.0] if x in list_A else [0.0]
    for x in list_B}

You may want to make list_A a set first, to make in membership tests efficient (O(1)); a list takes O(N) linear time to determine membership:

set_A = set(list_A)
my_variable = {
    x: [7.0] if x in set_A else [0.0]
    for x in list_B}
Comments