tincan
tincan

Reputation: 412

How to pass multiple elements in dictionary to replace values python

I want to pass a full array into a dictionary as keys and get the values out:

dic = {1:'a', 2:'b', 3:'c'}
lista = [1,2,3]

dic.get(1)
'a'

dic.get(list)
error

thanks

Upvotes: 1

Views: 93

Answers (4)

BENY
BENY

Reputation: 323226

We can do map

[*map(dic.get,lista)]
Out[270]: ['a', 'b', 'c']

Upvotes: 0

Vivek Kalyanarangan
Vivek Kalyanarangan

Reputation: 9081

Use -

dic = {1:'a', 2:'b', 3:'c'}
list_ = [1,2,3]

a = [dic.get(k) for k in list_]

@Ch3steR

453 ns ± 192 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

-->thisone

888 ns ± 430 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

Upvotes: 3

tincan
tincan

Reputation: 412

in pandas its called the map function:

lista = lista.map(dic)

cheers

Upvotes: 0

Ch3steR
Ch3steR

Reputation: 20669

You could use operator.itemgetter here.

from operator import itemgetter

dic = {1:'a', 2:'b', 3:'c'}
lst = [1, 2, 3]
itemgetter(*lst)(dic)
# ('a', 'b', 'c')

Upvotes: 3

Related Questions