0

I have a dictionary:

d = {'a': 1, 'b': 2, 'c': 3}

and a list:

l = ['a', 'c']

How do I obtain a list of the dictionary values from the list above? i.e. I want:

[1, 3]

I've tried:

d[l]

but get the following error: TypeError: unhashable type: 'list'.

ajrlewis
  • 2,968
  • 3
  • 33
  • 67

3 Answers3

1

You can do list comprehension:

values = [d[x] for x in l]
Matias Cicero
  • 25,439
  • 13
  • 82
  • 154
1
[d[key] for key in l]

Python itself doesn't do vectorized expressions like the one you tried.

Prune
  • 76,765
  • 14
  • 60
  • 81
0

you can use list comprheension:

d = {'a': 1, 'b': 2, 'c': 3}
l = ['a', 'c']
res = [d[key] for key in l]
developer_hatch
  • 15,898
  • 3
  • 42
  • 75