1

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

1
  • I know i cant use list as a variable, please pretend its lista (I also know its an array) Commented Jan 19, 2022 at 16:15

4 Answers 4

3

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')
Sign up to request clarification or add additional context in comments.

1 Comment

@VivekKalyanarangan Thank you. I did not timeit but good to know :)
3

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)

Comments

0

in pandas its called the map function:

lista = lista.map(dic)

cheers

1 Comment

Is lista Series object?
0

We can do map

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.