'Adding values to an empty dictionary from an existing one throws TypeError: unsupported operand type(s) for +: 'int' and 'list',

Want to get sum of the values using sum function but Keep on getting TypeError: unsupported operand type(s) for +: 'int' and 'list'

ones = {'alpha': [2662.0,80], 'beta': [3646.7,50], 'gamma': [250.8,100]}
twos = {}

for k,(v,q) in ones.items():
    if k not in twos:
        twos[k] = []
    twos[k].append(v)
print(twos)

sum_twos = sum(twos.values())
print(sum_twos)


Solution 1:[1]

I found another way to do it: by not storing the values to new dictionary in lists, instead storing them in float.

ones = {'alpha': [2662.0,80], 'beta': [3646.7,50], 'gamma': [250.8,100]}
twos = {}

for k,(v,q) in ones.items():
    if k not in twos:
        twos[k] = float()
    twos[k] += v
print('twos','=', twos)

sum_twos = sum(twos.values())
print('sum_twos',':', sum_twos)

Output: twos = {'alpha': 2662.0, 'beta': 3646.7, 'gamma': 250.8}

sum_twos : 6559.5

Solution 2:[2]

A bit weird, but a solution can be:

ones = {
    'alpha': [2662.0,80],
    'beta': [3646.7,50],
    'gamma': [250.8,100]
}
twos = {}

for k,(v,q) in ones.items():
    if k not in twos:
        twos[k] = []
    twos[k].append(v)

sum_twos = sum([sum(v) for v in twos.values()])
print(sum_twos)

Output:

6559.5

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Praveen Paliwal
Solution 2 Davide Madrisan