2

Is there a more efficient and/or python way to make the following list conversion using a dictionary?

d = {1:2, 2:3, 3:4}
e = [1 , 1, 2, 2, 3, 1]
f=[]
for l in e:
    f.append(d[l])
f
Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
SantoshGupta7
  • 5,607
  • 14
  • 58
  • 116

1 Answers1

2

Use a map (Efficient)

f = map(d.get, e)

For larger data set and complex manipulations use pandas

>>> import pandas as pd
>>> s = pd.Series(e)
>>> s.map(d)

Use list comprehension

f = [d[key] for key in e]

Timings

For a list of 1000 items,

List Comprehension: 2.346038818359400 × 10-4

Map: 9.059906005859375 × 10-6

Vishnudev Krishnadas
  • 10,679
  • 2
  • 23
  • 55
  • 1
    Technically, map function returns a generator object, not a list, so your timing measurements make little sense – Lesiak Oct 28 '19 at 05:51
  • 2
    The reason map *appears* to be faster is that it doesn't actually do anything, being a lazy generator. For a fair comparison (and to get the type OP is actually looking for), wrap the `map` in `list` – Mad Physicist Oct 28 '19 at 05:53
  • @Lesiak *technically* `map` returns a `map` object, which is not a generator – juanpa.arrivillaga Oct 28 '19 at 06:25