简体   繁体   中英

Python Function sum even values from a dictionary

I am trying to write a function that receives a dictionary similar to this:

A = {'one':1,'two':2,'three':3,'four':4}

and if it is even it will sum the value, if it is odd or not numeric it will skip it. This is my current work:

def sumEven(entry):
    
    count1=0
    
    for i in entry:
        a=int(entry[i])
        if(a % 2 == 0):
            count1 + i
    return
TypeError: unsupported operand type(s) for +: 'int' and 'str'

I can't figure out where the str value is coming from.

You can also perform sum using python built-in sum .

sum(value for value in A.values() if value % 2 == 0)

Note: this will not work if the dictionary values are not integers

Change:

            count1 + i

To:

            count1 += a

Explanation:

def sumEven(entry):
    
    count1 = 0 # 0 is an integer
    for i in entry: # For i in entry is the as for every key in entry, where the keys are strings
        a = int(entry[i])
        if (a % 2 == 0):
            count1 + i # So here, you are adding a string to an integer
    return

I think your code should be:

def sumEven(entry):
    count1=0

    for key, value in entry.items():
       if(value % 2 == 0):
           count1 += value
    return count1

Note that:

  • I used entry.items() to extract both the key and the value at the same time; your code just extracted the keys, and you needed a separate line to extract the value.
  • You need to use += when adding the value to count1 - using + as you did will not store the calculated value
  • I deliberately used readable variables (rather than i and a ) - it is a good habit to get into
  • You need to return the value you calculate.

Try this:

def sumEven(entry):
    count1=0
    for i in entry.values():
        a = i
        if a % 2 == 0:
            count1 += a
    return count1

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