-3

How to transform every element of list according to dictionary? For example: I have list:

l = [0,1,2,3,2,3,1,2,0]

and I have a dictionary:

m = {0:10, 1:11, 2:12, 3:13}

I need to acquire list:

[10, 11, 12, 13, 12, 13, 11, 12, 10]
Sklavit
  • 2,225
  • 23
  • 29
  • 3
    Did you spend any time at all looking for an existing question on this? – TigerhawkT3 Dec 24 '15 at 10:35
  • Yes. And in opposite to the most answers of your link, I have duplicated keys. Also, there is no speed test there. – Sklavit Dec 24 '15 at 11:36
  • 1. I said "question." 2. What difference do duplicate keys make? 3. Your results could have been an answer on an existing question, or even a comment on an answer. – TigerhawkT3 Dec 24 '15 at 11:49
  • 1. I search and didn't find that question. It must be because I don't think about it in terms of key/value, but in terms of map. – Sklavit Dec 24 '15 at 23:06
  • 2. Code like ' [v for k, v in mydict.items() if k in mykeys]' will return only values for unique keys. – Sklavit Dec 24 '15 at 23:07
  • 3. Thank you for your link, I added my answer there too. – Sklavit Dec 24 '15 at 23:09

1 Answers1

-1

There are several ways to do this:

In[1]: l = [0,1,2,3,2,3,1,2,0]
In[2]: m = {0:10, 1:11, 2:12, 3:13}
In[3]: %timeit [m[_] for _ in l]  # list comprehension
1000000 loops, best of 3: 762 ns per loop
In[4]: %timeit map(lambda _: m[_], l)  # using 'map'
1000000 loops, best of 3: 1.66 µs per loop
In[5]: %timeit list(m[_] for _ in l)  # a generator expression passed to a list constructor.
1000000 loops, best of 3: 1.65 µs per loop
In[6]: %timeit map(m.__getitem__, l)
The slowest run took 4.01 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 853 ns per loop
In[7]: %timeit map(m.get, l)
1000000 loops, best of 3: 908 ns per loop
In[33]: from operator import itemgetter
In[34]: %timeit list(itemgetter(*l)(m))
The slowest run took 9.26 times longer than the fastest. This could mean that an intermediate result is being cached 
1000000 loops, best of 3: 739 ns per loop

So list comprehension is the fastest way to do this.

Sklavit
  • 2,225
  • 23
  • 29