Mapping Python list based on dict value

Viewed 42

I want to map python list based on values of dict. I know how to do that when I have pandas series, but I do not know how to do it with list:

l = ['apple', 'lemmon', 'banana']
x = {'apple':1, 'lemmon':2, 'banana':3, 'chery':4}

l = l.map(x)
print(l)

Desired output:

l = [1,2,3]
3 Answers

This can be solved with Python list comprehensions. In your case:

l = [x[key] for key in l]

Note that all elements in l need to exist as keys in x.

Using the dict.get method and the map builtin:

m = list(map(x.get, l))

Note that elements of l that are not keys of x will be mapped to None.

With a comprehension:

>>> [x.get(i) for i in l]
[1, 2, 3]
Related