简体   繁体   中英

Python: Sum of certain values of a dictionary

dict = {'A': 71.07884,
    'B': 110
    'C': 103.14484,
    'D': 115.08864,
    'E': 129.11552,
    'F': 147.1766,
   }

name = "ABC"

for character in name:
    for key, value in dict.items():
        if key == character:
            print(value)

I have a dictionary dict and a string name. Now I want to sum the values of dict that are equals with characters of the string name.

With my solution I just get the values 71.07884, 110, 103.14484 but how I can sum this values.

If I try print(sum(value)) I get this: TypeError: 'float' object is not iterable.

I'm new in python :)

You can do it that way - initialize an empty list first and then everytime you get the value in the loop, append it to the list. You'll get a list [71.07884, 110, 103.14484] , which you can then sum.

dict = {'A': 71.07884,
    'B': 110,
    'C': 103.14484,
    'D': 115.08864,
    'E': 129.11552,
    'F': 147.1766,
   }

name = "ABC"
values = []
for character in name:
    for key, value in dict.items():
        if key == character:
            values.append(value)
sum(values)

Output:

sum(values)
Out[6]: 284.22368

You can do it like this:

mydict = {'A': 71.07884,
    'B': 110,
    'C': 103.14484,
    'D': 115.08864,
    'E': 129.11552,
    'F': 147.1766,
   }

name = "ABC"

sum(value for key, value in mydict.items() if key in name)

# 284.22368

Note that I renamed your dictionary to mydict , as dict is a Python builtin function, which you shouldn't use as a variable name.

You will get that error because the value changes as per its iterator. Inorder to find the sum you need to store and add the values to another variable and then call sum() or you could add it to a new variable.

What the sum() does is take a list and iterate through it. In your code what it is doing is passing the current value in the loop only so 1 value.

Example: Note (There are many ways to do this.)

name = "ABC"
sum = 0
for character in name:
    for key, value in dict.items():
        if key == character:
            print(value)
            sum = value + sum

print(sum) 

I think you need this:

list_name = "ADF"    
sum([value for key, value in dict.items() if key in list_name])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM