Sean Wade Sean Wade - 4 months ago 12
Python Question

How to change values in a list by using dict definitions python?

I have a list

l = [1, 1, 2, 1, 3, 3, 1, 1, 1, 3]
and I want to use my dict
d = {1:'r', 2:'b', 3:'g'}
to get the result
l = [r, r, b, r, g, g, r, r, r, g]
? What is the most pythonic way to achieve this?

Answer

Most Pythonic is probably a list comprehension:

l = [d[x] for x in l]

For larger inputs, the following might be faster, but less Pythonic, as it pays a slightly higher setup cost but (on CPython reference interpreter) pushes the per-element work to the C layer, bypassing the (relatively slow) byte code interpreter:

l = list(map(d.__getitem__, l))  # `list()` wrapping should be omitted on Python 2