[Solved] Replace list item with corresponding dictionary value [closed]


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)
11

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))]
['11']

1

solved Replace list item with corresponding dictionary value [closed]