Incorporate duplicates in a list of tuples into a dictionary summing the values
<p>Hi I wish to convert this list of tuples into dictionary. As I am new to python, I am figuring out ways to convert into dictionary. I could only convert into dictionary if there is only one value. In my case, there are two values in it.I will demonstrate with more details below:</p>

<pre><code>    `List of tuples: [('Samsung', 'Handphone',10), ('Samsung', 'Handphone',-1),
('Samsung','Tablet',10),('Sony','Handphone',100)]`
</code></pre>

<p>As you can see above, I wish to identify 'Samsung' as the key and 'Handphone' and '10' as the values with respect to the key.</p>

<p>My desired output would be:</p>

<pre><code>  `Output: {'Sony': ['Handphone',100], 'Samsung': ['Tablet',10,'Handphone', 9]}`
</code></pre>

<p>As you can see above, the item 'handphone' and 'tablet' are group according to the key values which in my case is Sony and Samsung. The quantity of the item are are added / subtracted if they belong to the same item and same key (Samsung or Sony).</p>

<p>I would really appreciate any suggestions and ideas that you guys have in order to achieve the above output. I really ran out of ideas. Thank you. </p>

<p>Your output has a problem, that can be seen with proper identation:</p>

<pre><code>{
    'Sony': ['Handphone',100], 
    'Samsung': ['Tablet',10],
    ['Handphone', 9]
}
</code></pre>

<p>Handphone isn't a part of 'Samsung', you can do a list of lists to get:</p>

<pre><code>{
    'Sony': [
        ['Handphone',100]
    ],
    'Samsung': [
        ['Tablet',10],
        ['Handphone', 9]
    ]
}
</code></pre>

<p>With:</p>

<pre><code>my_list = [('Samsung', 'Handphone',10), ('Samsung', 'Handphone',-1), ('Samsung','Tablet',10),('Sony','Handphone',100)]

result = {}
for brand, device, value in my_list:
    # first verify if key is present to add list for the first time
    if not brand in result:
        result[brand] = []
    # then add new list to already existent list
    result[brand] += [[device, value]]
</code></pre>

<p>But I think the best format would be a dict:</p>

<pre><code>{
    'Sony': {
        'Handphone': 100
    },
    'Samsung': {
        'Tablet': 10,
        'Handphone': 9
    }
}
</code></pre>

<p>That would be like:</p>

<pre><code>my_list = [('Samsung', 'Handphone',10), ('Samsung', 'Handphone',-1), ('Samsung','Tablet',10),('Sony','Handphone',100)]

result = {}
for brand, device, value in my_list:
    # first verify if key is present to add dict for the first time
    if not brand in result:
        result[brand] = {}
    # then add new key/value to already existent dict
    result[brand][device] = value
</code></pre>

python list dictionary tuples counter