user2914540 user2914540 - 1 year ago 70
Python Question

Pythonic way to find and replace with a dictionary of lists

I have this dictionary:

dic = {
'foo': ['one', 'two', 'three'],
'bar': ['four', 'five', 'six'],
'baz': ['seven', 'eight', 'nine']

and from this list:

my_list = ('one', 'five', 'nine')

I want to search the corresponding key in the dictionary in order to get this new list:

('foo', 'bar', 'baz')

My actual working code is:

l = []
for el in my_list:
for d_key, d_val in dic.items():
if el in d_val:


But I think there is a more Pythonic way. Any ideas?

Answer Source

I would first reverse the dictionary:

invdic = {val: key for key in dic for val in dic[key]}

Then you can apply the substitution:

l = ('one', 'five', 'nine')
l = tuple(invdic[x] for x in l)

EDIT: If you need to leave the keyword as is, when the dictionary does not contain the match, you can replace the second line with:

l = tuple(invdic.get(x, x) for x in l)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download