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?
Keys of a dict have to be hashable, which a list, such as x, is not, which is why you're getting the TypeError: unhashable type: 'list' error when you try to use x as a key to index the dict d.
If you're trying to perform bulk dictionary lookup you can use the operator.itemgetter method instead:
from operator import itemgetter
itemgetter(*x)(d)
This returns:
(1, 1, 3)
If you're working with default python you can do a list comprehension:
result = [d[i] for i in x]
If you are open to numpy solutions you can use conditional replacement. This will probably be the fastest on large inputs:
import numpy as np
result = np.array(x)
for k, v in d.items(): result[result==k] = v
Finally pandas has a .replace
import pandas as pd
result = pd.Series(x).replace(d)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With