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>

<p>You can't use the <em>key-value</em> pair in the <code>else</code> part of ternary conditional like so. </p>

<p>Do this instead:</p>

<pre><code>new_dict = {k: d1[k] if k in d1 else d2[int(k)]  for k in 'abc123'}
#                                    ^^&lt;- make value d2[int(k)] on else
print(new_dict)
#{'2': 2, '1': 1, 'b': 'b', 'a': 'a', 'c': 'c', '3': 3}
</code></pre>

<p>Note that <code>if k in d1</code> checks if <code>k</code> is a key in the dictionary <code>d1</code>. No need to call the <code>keys</code> method.</p>

python dictionary list-comprehension