Pythonic way to replace values in a list according to a dictionary

Viewed 162

I need to convert a list values according to values contained into a Python dictionary.

I have a list as the following:

lst = ["hello", "word", "bye", "my", "friend", "hello"]

And a dictionary obtained using a cluster procedure, so the keys are the labels and the values the categories:

my_dict = {0: ["hello", "word"], 1: ["my", "friend"], 2: ["bye"]}

I need to faster convert the original list into:

new_lst = [0, 0, 2, 1, 1, 0]

Consider that in the real case the list length is near 60k and so I need an efficient way to do this operation.

3 Answers
lst = ["hello", "word", "bye", "my", "friend", "hello"]
my_dict = {0: ["hello", "word"], 1: ["my", "friend"], 2: ["bye"]}

inverse_dict = {b:a for a,c in my_dict.items() for b in c}

new_lst = [inverse_dict.get(a) for a in lst]

For anyone interested in doing this in pandas:

my_dict = {0: ["hello", "word"], 1: ["my", "friend"], 2: ["bye"]}
# revert the dict
my_dict_rev = {k2: k for k, v in my_dict.items() for k2 in v}
# convert the list to a pandas Series
ser = pd.Series(["hello", "word", "bye", "my", "friend", "hello"])
# replace the values
rev_ser = ser.replace(my_dict_rev)

I know that the answer is not asking for a pandas solution, but especially for large lists, pandas will probably be substantially faster. Also perhaps someone else already using pandas will see this.

Easy to do this with simple list-comprehension also. No need to use Pandas .

lst = ["hello", "word", "bye", "my", "friend", "hello"]
my_dict = {0: ["hello", "word"], 1: ["my", "friend"], 2: ["bye"]}

result = []
[result.append(k) for word in lst for k,v in my_dict.items() if word in v]

print(result)

Output:

[0, 0, 2, 1, 1, 0]
Related