I try to sum per fruit sort the total.
So I have it:
listfruit= [('Watermeloenen', '123,20'), ('Watermeloenen', '2.772,00'), ('Watermeloenen', '46,20'), ('Watermeloenen', '577,50'), ('Watermeloenen', '69,30'), ('Appels', '3.488,16'), ('Sinaasappels', '137,50'), ('Sinaasappels', '500,00'), ('Sinaasappels', '1.000,00'), ('Sinaasappels', '2.000,00'), ('Sinaasappels', '1.000,00'), ('Sinaasappels', '381,25')]
def total_cost_fruit_per_sort():
number_found = listfruit
fruit_dict = {}
for n, f in number_found:
fruit_dict[f] = fruit_dict.get(f, 0) + int(n)
result = '\n'.join(f'{key}: {val}' for key, val in fruit_dict.items())
return result
print(total_cost_fruit_per_sort())
So that it looks like:
Watermeloenen: 800
Sinaasappels: 1000
But if I run the code I get this error:
File "c:\Users\engel\Documents\python\code\extract_text.py", line 292, in <genexpr>
result = sum(int(n) for _, n in listfruit)
ValueError: invalid literal for int() with base 10: '123,20'
But I parse the second value to an int, even when I try to do it to parse to float. Doesn’t work.
Question: how can I can calculate total of each fruit sort?
>Solution :
Here’s a solution exploiting .replace to handle . and , in the strings and eval to transform them to numeric.
def total_cost_fruit_per_sort(debug=False):
number_found = listfruit
fruit_dict = {}
for f, n in number_found:
parsed_n = eval(n.replace('.', '').replace(',', '.'))
if debug:
print(f, n, parsed_n)
fruit_dict[f] = fruit_dict.get(f, 0) + parsed_n
result = '\n'.join(f'{key}: {val}' for key, val in fruit_dict.items())
return result
print(total_cost_fruit_per_sort())
This gives as output:
Watermeloenen: 3588.2
Appels: 3488.16
Sinaasappels: 5018.75
In case you want to double check the string-to-numeric conversions you can run the function with the argument debug=True enabled.