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>As described, it seems like both your <code>d1</code> and <code>d2</code> are artifacts of how you envision solving the problem and aren't essential.  How about simply:</p>

<pre><code>&gt;&gt;&gt; dictionary = {k: int(k) if k.isdigit() else k for k in 'abc123'}
&gt;&gt;&gt; dictionary
{'b': 'b', '3': 3, '2': 2, '1': 1, 'a': 'a', 'c': 'c'}
&gt;&gt;&gt; 
</code></pre>

<p>Or is there more to the problem you're trying to solve?</p>

python dictionary list-comprehension