Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python conditional dictionary comprehension

Is there a reason why this list comp works:

N = 5
d = {0:100, 2:5}
[(dpidx,d[dpidx]) if dpidx in d else (dpidx,dpidx) for dpidx in range(N)]

[(0, 100), (1, 1), (2, 5), (3, 3), (4, 4)]

but this dict comp doesn't work? :

{dpidx:d[dpidx] if dpidx in d else dpidx:dpidx for dpidx in range(N)}

{dpidx:d[dpidx] if dpidx in d else dpidx:dpidx for dpidx in range(N)}
                                        ^
SyntaxError: invalid syntax

I'm looking for:

{0: 100, 1: 1, 2: 5, 3: 3, 4: 4}

I thought I could just use a dict comp instead of a dict(list comp).

Thanks in advance!

like image 489
jkmacc Avatar asked Mar 29 '26 22:03

jkmacc


1 Answers

You cannot repeat the key. A dictionary comprehension has the form

{k: v for ...}

where k and v are expressions. One (or both) of these expressions can be a conditional expression, which will give

{dpidx:d[dpidx] if dpidx in d else dpidx for dpidx in range(N)}

But k: v is not an expression in its own right.

An easier way to write this is

{dpidx:d.get(dpidx, dpidx) for dpidx in range(N)}
like image 69
Sven Marnach Avatar answered Apr 02 '26 03:04

Sven Marnach