How to return the sum for each string value in excel sheet?


I try to return the sum for every fruit item.

So I have a excel sheet with column E(5) and then for every row there is a value.

So the row:ananas(6,7,8) has the values: 1596, 1309,1057 = total: 3962

So I have it like this:

import openpyxl
import tabula

excelWorkbook = openpyxl.load_workbook(path, data_only=True)
def calulate_total_fruit_NorthMidSouth():

    sheet_factuur = excelWorkbook['Facturen ']

    fruit_name_rows = {
        'ananas': [6, 7, 8],
        'apple': [9, 10, 11],
        'waspeen': [12, 13, 14],

    total_fruit_counts = {k:sum([sheet_factuur.cell(
        row=row_num, column=5)).value for row_num, in fruit_name_rows.items()]}

    return  total_fruit_counts

the output has to look like this:

apple: 200
waspeen: 700

my excel sheet looks like this:

Regio Noord Ananas  1,596.00
Regio Midden Ananas 1,309.00
Regio Zuid Ananas   1,057.00
Regio Noord Appel   1,333.80
Regio Midden Appel  1,090.44
Regio Zuid Appel    879.84
Regio Noord Waspeen 1,530.90
Regio Midden Waspeen    1,234.80
Regio Zuid Waspeen  1,001.70

ananas is colum 5 and row: 6,7,8 Appel is column 5 and row: 9,10,11
and Waspeen is column 5 and row: 12,13,14

Asked By: mightycode Newton



You could use a dictionary to keep a running tally of sums while you iterate through the values.

fruit_sums = {
    'ananas': 0,
    'apple': 0,
    'waspeen': 0,

I would recommend converting all excel values to a python array.

array = [row for row in sheet_factuur.values]

Iterate through values and add them to your fruit_sums.

for row_num, row_values in enumerate(array, 1):  # excel does not have a row 0
    for fruit in ['ananas', 'apple', 'waspeen']:  # loop through specific fruits
        if row_num in fruit_name_rows[fruit]:
            fruit_sums[fruit] += row_values[4]  # index 4 is column 5 in excel

Then display or save the data however you wish.

for fruit, s in fruit_sums.items():  
    print(f'{fruit.rjust(10)} {s}')

>> ananas     3962
>> apple      200
>> waspeen    700
Answered By: stan61285
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.