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

Summation with values in a dictionary (Python)

I am struggling with using summation in Python.

I obtain input, which is then autocorrected and all punctuation is removed:

text=input("Enter your text here: )

Then, I have a dictionary:

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

bread = {"bread": 7, "sourdough crusts": 10}

I determined if any key from bread existed in text with the code:

result = re.findall('|'.join(bread), text)

I want to find the sum of all the values, should the corresponding key exist in text. At the moment, my code looks like this:

for sentence, rating in bread.items():
     ssum = 0
     for i in range(len(result)):
           ssum = ssum + rating
print("Sum: " + str(ssum))

However, this produces incredibly random results. For example, if

text = bread sourdough crusts

It says that

ssum = 20

(even though it should equal 17).

What is going on here, and how do I fix it?

>Solution :

By adding print(ssum) after the add you might get a good idea what is going on and why the result is "random".

7
14
10
20
Sum: 20

Each sentence rating is added len(result) times, but you are assigning ssum = 0 on each loop iteration, so you return only the last one.
Instead, you want to simply check if the sentence is found in result and assign ssum outside the loop

import re

text = "bread sourdough crusts"
bread = {"bread": 7, "sourdough crusts": 10}
result = re.findall('|'.join(bread), text)
ssum = 0
for sentence, rating in bread.items():
    if sentence in result:
        ssum = ssum + rating
print("Sum: " + str(ssum))
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