'How to efficiently use a dictionary and a list of keys to find a list of values

For example, I have a pandas data frame df like this:

    A  B
0  12  ['key1', 'key2']
1  23  ['key3', 'key4']

and I have a dictionary dic like this:

{'key1': 'value1', 'key2': 'value2', 'key3': 'value3'}

and I want to generate a column df['C'] such that every element in the list in it are the values corresponding with the key in the lists of df['B']:

    A  B                 C
0  12  ['key1', 'key2']  ['value1', 'value2']
1  23  ['key3', 'key4']  ['value3', nan]

How can I achieve this in a time efficient manner? Thanks!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source