Creating a dictionary with multiple values per key from a list of dictionaries
<p>I have the following list of dictionaries:</p>

<pre><code>listofdics = [{'StrId': 11, 'ProjId': 1},{'StrId': 11,'ProjId': 2},
              {'StrId': 22, 'ProjId': 3},{'StrId': 22, 'ProjId': 4},
              {'StrId': 33, 'ProjId': 5},{'StrId': 33, 'ProjId': 6},
              {'StrId': 34, 'ProjId': 7}]
</code></pre>

<p>I need to get all <code>ProjId</code> values for <code>StrId</code> that are duplicate. So this is the output I'm looking for:</p>

<pre><code>new_listofdics = [{11:[1,2]}, {22:[3,4]}, {33:[5,6]], {34:[7]}]
</code></pre>

<p>I wrote a function that creates a list of dictionaries with <code>StrId</code> values as keys, and a list with all <code>ProjId</code> that share the same key as values. Here it is:</p>

<pre><code>def compare_projids(listofdics):
    proj_ids_dups = {} 

    for row in listofdics:       
        id_value = row['StrId']
        proj_id_value = row['ProjId']
        proj_ids_dups[id_value]=proj_id_value

        if row['StrId'] == id_value:
            sum_ids = []
            sum_ids.append(proj_id_value)  
        proj_ids_dups[id_value]=sum_ids
     return proj_ids_dups
</code></pre>

<p>This is the output I get now:</p>

<pre><code>new_listofdics=  {33: [6], 34: [7], 11: [2], 22: [4]}
</code></pre>

<p>What I see is that<code>append</code> replaces each <code>ProjId</code> value with the last one iterated, instead of adding them at the end of the list.</p>

<p>How can I fix this?...</p>

<p>It's unclear why you need to have such output <code>new_listofdics = [{11:[1,2]}, {22:[3,4]}, {33:[5,6]], {34:[7]}]</code>, because it's better to have just <code>dict</code> object.</p>

<p>So program would look like this</p>

<pre><code>&gt;&gt;&gt; from collections import defaultdict
&gt;&gt;&gt; listofdics = [{'StrId': 11, 'ProjId': 1},{'StrId': 11,'ProjId': 2},
              {'StrId': 22, 'ProjId': 3},{'StrId': 22, 'ProjId': 4},
              {'StrId': 33, 'ProjId': 5},{'StrId': 33, 'ProjId': 6},
              {'StrId': 34, 'ProjId': 7}]
&gt;&gt;&gt; output = defaultdict(list)
&gt;&gt;&gt; for item in listofdics:
...     output[item.get('StrId')].append(item.get('ProjId'))
&gt;&gt;&gt; dict(output)
{11: [1, 2], 22: [3, 4], 33: [5, 6], 34: [7]}
</code></pre>

<p>It's much easier to go through that dict that your desired output.</p>

python dictionary