user2914540 user2914540 - 4 months ago 9
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:
l.append(d_key)

print(l)


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

Answer

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)
print(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)