Will W Will W - 4 months ago 21
Python Question

Replace list item with corresponding dictionary value

My dictionary is

{'apple': '2', 'banana': '3', 'pear': '1', 'peach': '1'}

And my list is

['banana', 'apple', 'pear', 'apple banana']

How would I make a new list replacing the list values with the dictionary values?
This is what the new list should be.

['3', '2', '1', '5']

And how would I add all the values up to get a new list with the numbers added inside like this


I have tried:

result = map(dictionary.get, l)

But this gives the wrong answer:
['3', '2', '1', None]


Let's define your variables:

>>> d = {'apple': '2', 'banana': '3', 'pear': '1', 'peach': '1'}
>>> x = ['banana', 'apple', 'pear', 'apple banana']

Now, let's compute the results:

>>> [sum(int(d[k]) for k in y.split()) for y in x]
[3, 2, 1, 5]
>>> sum(sum(int(d[k]) for k in y.split()) for y in x)

Or, if the first list above really needed to have strings for its elements and the sum above also needed to be string and in a list:

>>> [str(sum(int(d[k]) for k in y.split())) for y in x]
['3', '2', '1', '5']
>>> [str(sum(sum(int(d[k]) for k in y.split()) for y in x))]