Sum values in dictionary
<p>I'm working with an Excel file and openpyxl.</p>

<p>Below is sample data:</p>

<pre><code>Name    Value
Amy1    4
Bob1    5
Bob1    5
Bob2    8
Chris1  7
Chris2  3
Chris3  6
Chris3  6
Chris3  6
</code></pre>

<p>Using the for loop below, I grab the value associated with each unique name.</p>

<pre><code>for rowNum in range(2, 11):
    person = sheet.cell(row = rowNum, column = 13).value
    people.append(person)
    personValue.update({person: sheet.cell(row = rowNum, column = 26).value})
</code></pre>

<p>That yields a dictionary with a single entry for each name (Amy1, Bob1, Bob2, etc.).</p>

<p>I want to merge and sum the value for each matching name to return the following result:</p>

<pre><code>Name  Value
Amy   4
Bob   13
Chris 16
</code></pre>

<p>You can use the <code>get()</code> method to set a default value for a key and then add to it that way.</p>

<p>Since all of your keys are in the format name#, you can get the end result you want like this:</p>

<pre><code>mergedResult = dict()

for name in startingDict:
    mergedResult[name[:-1]] = mergedResult.get(name[:-1], 0) + startingDict[name]
</code></pre>

<p>Here, the <code>get()</code> method checks for a key <code>name[:-1]</code> (the name from your starting dictionary without the final character) in your result dictionary. If that key isn't present, it adds it with a default value of 0 and returns that value. If that key is already present, it simply returns the corresponding value. Then, the value from your starting dictionary is added to the value in your result dictionary.</p>

python list dictionary sum