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

Time:05-11

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

CodePudding user response:

Try this (dct is your dictionary):

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

CodePudding user response:

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'}

CodePudding user response:

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.

  • Related