Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to sum second element in each tuple in string, if second value is string?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading