Arpit Agarwal
Arpit Agarwal

Reputation: 527

Replace a list item with the value of the item stored in dictionary in python

I have a list and a dictionary and I want to replace the list item with the value of the dictionary. A simplified version of my problem is as follows:

#This is a list
a=['dog', 'cat', 'cow']

#This is a dictionary
b={'dog': 'barks', 'cat': 'meows', 'cow': 'moos' } 

Now list a[0] i.e dog is searched in the dictionary b and key dog will be found and I want its value barks in place of dog in the list a.

Expected output should be something like this

a=['barks','meows','moos']

I have been able to do this with the help of three text files in which one text file had the format 'key-value' and in other two I extracted key and values respectively with the help of split() function and then later matching the index position to get the desired result. But, the problem is that the code is way too long. I tried to do the above approach which I asked but couldn't get to replace the values.

Upvotes: 2

Views: 172

Answers (3)

Alex Kreimer
Alex Kreimer

Reputation: 1106

There probably are lots of ways to do that, here is one more:

map(b.get, a)

or

map(lambda x: b[x],a)

Link to the map doc: https://docs.python.org/2/library/functions.html#map

Upvotes: 6

TigerhawkT3
TigerhawkT3

Reputation: 49320

If you want the list modified in-place:

a=['dog', 'cat', 'cow']
b={'dog': 'barks', 'cat': 'meows', 'cow': 'moos' }
for idx,value in enumerate(a):
    a[idx] = b[value]

Upvotes: 3

Cory Kramer
Cory Kramer

Reputation: 117856

You can index out of the dictionary using a list comprehension

>>> a = [b[i] for i in a]
>>> a
['barks', 'meows', 'moos']

Upvotes: 6

Related Questions