Use else in dict comprehension
<p>From two dictionaries:</p>

<pre><code>d1 = {a:a for a in 'abcdefg'}
d2 = {n:n for n in range(10)}
</code></pre>

<p>How can I create a third one like:</p>

<pre><code>new_dict = {k:d1[k] if k in d1.keys() else k:d2[k]  for k in 'abc123' }
</code></pre>

<p>It's throwing a syntax Error, but with list comprehension seems to be fine:</p>

<pre><code>[a if a else 2 for a in [0,1,0,3]]
out[]: [2, 1, 2, 3]
</code></pre>

<p>Moreover, why this works:</p>

<pre><code>{k:d1[k]  for k in 'abc123' if k in d1.keys() }
</code></pre>

<p>and this doesn't:</p>

<pre><code>{k:d1[k] if k in d1.keys() for k in 'abc123' }
</code></pre>