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!
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)}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With