dissidia
dissidia

Reputation: 1581

Sum of string values of a list in dictionary

I am having trouble deriving the overall sum of string values. While I am able to generate the following if there are in integers form:

size = {
    'serverA' : [10, 10],
    'serverB' : [3, 3, 3],
}

If I used sums = {k: sum(i for i in v if isinstance(i, int)) for k, v in size.items()}, I will be able to get output such as {'serverA': 20, 'serverB': 9}

However, instead of having integers in the values of the list, I got string as follows:

size = {
    'serverA' : ['10', '10'],
    'serverB' : ['3', '3', '3'],
}

And if I used the same command to generate the sum of values, while there are no errors, the sums are clearly wrong in which the output is {'serverA': 0, 'serverB': 0}

Upvotes: 0

Views: 1173

Answers (2)

Kyle P
Kyle P

Reputation: 152

Simply use int(integer_string)

sums = {k: sum(int(i) for i in v) for k, v in size.items()}

Also, keep in mind using isinstance is typically considered an antipattern. If you want type checking check out Python 3.6 type annotations or use a different language.

Upvotes: 2

AChampion
AChampion

Reputation: 30288

You can use map() to map the values to ints:

>>> {k: sum(map(int, v)) for k, v in size.items()}
{'serverA': 20, 'serverB': 9}

Note: if you have values that aren't integers this will raise a ValueError exception.
Don't really understand why you had the isintance(i, int) in your base case.

Upvotes: 3

Related Questions