Stuck defining composition function in python
<p>input: two functions f and g, represented as dictionaries, such that g â¦ f exists. output: dictionary that represents the function g â¦ f. 
example: given f = {0:âaâ, 1:âbâ} and g = {âaâ:âappleâ, âbâ:âbananaâ}, return {0:âappleâ, 1:âbananaâ}.</p>

<p>The closest to the correct answer I have is with {i:g[j] for i in f for j in g} which outputs {0: 'apple', 1: 'apple'}. What am I doing wrong?</p>

<p>The correct dict comprehension would be:</p>

<pre><code>{i:g[f[i]] for i in f}
</code></pre>

<p>You did:</p>

<pre><code>{i:g[j] for i in f for j in g}
</code></pre>

<p>That mapped every i to every <code>i</code> to every value in <code>g</code>, but then dict removed duplicate keys.</p>

<p>To see what is going on, try generating a list instead:</p>

<pre><code>&gt;&gt;&gt; [(i, g[j]) for i in f for j in g]
[(0, 'apple'), (0, 'banana'), (1, 'apple'), (1, 'banana')]
</code></pre>

<p>In the correct case:</p>

<pre><code>&gt;&gt;&gt; [(i, g[f[i]]) for i in f]
[(0, 'apple'), (1, 'banana')]
</code></pre>

python composition