Keep identical values in default dict
<p>I have the following two lists:</p>

<pre><code>prefix = ['AGG', 'CAG', 'CAG', 'GAG', 'GGA', 'GGG', 'GGG']
suffix = ['GGG', 'AGG', 'AGG', 'AGG', 'GAG', 'GGA', 'GGG']
</code></pre>

<p>I am trying to use defaultdict to get this result:</p>

<pre><code>AGG -&gt; GGG
CAG -&gt; AGG,AGG
GAG -&gt; AGG
GGA -&gt; GAG
GGG -&gt; GGA,GGG
</code></pre>

<p>(Yes this is a Rosalind problem for those of you who know. I REALLY want to learn how to use dictionaries effectively though, so I am NOT looking for homework answers. Just dictionary help.) </p>

<p>This is my code: </p>

<pre><code>from collections import defaultdict
nodes = defaultdict(set)
for pre, suf in zip(prefix, suffix):
    nodes[pre].add(suf)
for k,v in nodes.items():
    print(k,v)
</code></pre>

<p>This is my result: </p>

<pre><code>CAG {'AGG'}
GAG {'AGG'}
GGG {'GGG', 'GGA'}
AGG {'GGG'}
GGA {'GAG'}
</code></pre>

<p>So I have two issues:</p>

<p>1) I need AGG, the value for CAG, to be preserved as two identical instances.</p>

<p>2) I cannot figure out how to print from my dictionary nicely, without brackets and quotes and to add in the arrow. </p>

<p>Thank you in advance! </p>

<p>Use a <code>defaultdict</code> of <code>list</code>, instead of <code>set</code>.  Sets removes duplicates.  </p>

<p>Your code is already fine, you'll just have to change the </p>

<pre><code>nodes[pre].add(suf)
</code></pre>

<p>to</p>

<pre><code>nodes[pre].append(suf)
</code></pre>

<p>For the printing, it will be like</p>

<pre><code>print('{} -&gt; {}'.format(k, ','.join(v)))
</code></pre>

python defaultdict