[Solved] Openpyxl & Python : column of keys, column of values – how to add up the values and assign totals to corresponding keys


Try this code:

# Define a dict{} for key:value pairs
ref_total = {}

# Get Data from all rows
for row in ws.rows:
    # Slice cells A,B from row tuple
    cell_A = row[:1][0]
    cell_B = row[1:2][0]

    reference = cell_A.value
    if reference in ref_total.keys():
        ref_total[reference] += cell_B.value
    else:
        ref_total[reference] = cell_B.value

for key in sorted(ref_total.keys()):
    print('%s %s' % (key, ref_total[key]))

Tested with Python:3.4.2 – openpyxl:2.4.1 – LibreOffice: 4.3.3.2

1

solved Openpyxl & Python : column of keys, column of values – how to add up the values and assign totals to corresponding keys