Home > Mobile >  How to format dictionary.items , so that it will return 2 marks after comma?
How to format dictionary.items , so that it will return 2 marks after comma?

Time:11-27

I have a excel sheet and I extract some values from the sheet. But some numbers extracted from the file sheet looks like:

3767.3999999999996

and it has to be: 3767,39. So just two decimals after comma.

I Tried with this function:

import openpyxl

def load_excel_file(self, file_name):
        excelWorkbook = openpyxl.load_workbook(filename=file_name, data_only=True)
        return excelWorkbook

def calulate_total_fruit_NorthMidSouth(self, file_name):

        # self.excelWorkbook
        sheet_factuur = self.load_excel_file(file_name)["Facturen "]

        fruit_sums = {
            "ananas": 0,
            "apple": 0,
            "waspeen": 0,
        }

        fruit_name_rows = {
            "ananas": [6, 7, 8],
            "apple": [9, 10, 11],
            "waspeen": [12, 13, 14],
        }
        array = [row for row in sheet_factuur.values]  # type: ignore

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

        return "\n".join(f"{a} {b}" for a, b in "{:.2%}".format(fruit_sums.items()))

I try to format the return statement. But I get this error:

TypeError at /controlepunt
unsupported format string passed to dict_items.__format__

Question: how to format this correct so that it have only two marks after comma?

CodePudding user response:

The issue is at "{:.2%}".format(fruit_sums.items()), but even if it had worked, you would have tried to iterate key, values on a string, that is absolutly not the way

You need to apply the formatting logic only the value only

return "\n".join(f"{a} {b:.2f}" for a, b in fruit_sums.items())
  • Related