Quentin - 5 months ago 26

Python Question

I would like to make a dictionary comprehension with

`if`

`else`

`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`

`else x:[0.0]`

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}
```