I have a large number of strings that I would like to convert to integers. What is the most concise way to perform a dictionary lookup of a list in Python 3.7?
For example:
d = {'frog':1, 'dog':2, 'mouse':3}
x = ['frog', 'frog', 'mouse']
result1 = d[x[0]]
result2 = d[x]
result
is equal to 1
but result2
is not possible:
TypeError Traceback (most recent call last)
<ipython-input-124-b49b78bd4841> in <module>
2 x = ['frog', 'frog', 'mouse']
3 result1 = d[x[0]]
----> 4 result2 = d[x]
TypeError: unhashable type: 'list'
One way to do this is:
result2 = []
for s in x:
result2.append(d[s])
which results in [1, 1, 3]
but requires a for loop. Is that optimal for large lists?