Will W - 11 months ago 57

Python Question

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

`['11']`

I have tried:

`result = map(dictionary.get, l)`

print(list(result))

But this gives the wrong answer:

`['3', '2', '1', None]`

Answer Source

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']
```