'How to add multiple values associated with one key in Python and display as an integer?

I have a dictionary which currently looks like this:

{'Target': [' $12', ' $17', ' $45'],
'Jamba Juice': [' $5', ' $8']}

How can I add the multiple values associated with each key and display it?

Expected Output:

Target: $74

Jamba Juice: $13



Solution 1:[1]

Try this (dct is your dictionary):

for k, lst in dct.items():
    print(f'{k}: ${sum(int(val[2:]) for val in lst)}')

Solution 2:[2]

Using a dictionary comprehension and str.partition:

d = {'Target': [' $12', ' $17', ' $45'],
     'Jamba Juice': [' $5', ' $8']}

out = {k: f"${sum(int(x.partition('$')[2]) for x in v)}"
       for k,v in d.items()}

output:

{'Target': '$74', 'Jamba Juice': '$13'}

Solution 3:[3]

some_dict = {'Target': [' $12', ' $17', ' $45'],
'Jamba Juice': [' $5', ' $8']}

for key,val in some_dict.items():
    print(key + ':',"$"+ str(sum(map(lambda s: int(s[2:]),val))))

Explanation:

Iterate over the keys and values of the dictionary, apply the lambda function (using map) to each string in the list of strings. The lambda func strips off the prefixes from the dollar amounts and converts them to integers, and then the sum function sums up the amounts together.

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 Riccardo Bucco
Solution 2 mozway
Solution 3 Jake Korman