Python replace comma separated words in list to dictionary value if existed in dictionary key

Tags:



I would like to replace words to corresponding dictionary key:value if exist. For example, I have a comma separated list

unfiltered = ['Cat,Dog,Cow','','Horse,Whale','Fish,Giant Elephant']

and would like to change ‘Whale’ to ‘Big Whale’ and ‘Fish’ to ‘Jellyfish’ like this dictionary:

word_to_change = {'Whale': 'Big Whale', 'Fish': 'Jellyfish'}

to make the result like this:

['Cat,Dog,Cow','','Horse,Big Whale','Jellyfish,Giant Elephant']

I could combine all the elements in ‘unfiltered’ list and filtered with dictionary value:

unfiltered_combine = ['Cat','Dog','Cow','','Horse','Whale','Fish','Giant Elephant']

[x if x not in word_to_change else word_to_change[x] for x in lists]

Result when filtering combined words:

['Cat', 'Dog', 'Cow', '', 'Horse', 'Big Whale', 'Jellyfish', 'Giant Elephant']

However, I want to keep the list ‘unfiltered’ without combining its elements. Is there any way to filter the ‘unfiltered’ list to ‘word_to_change’ dictionary key:value? I would sincerely appreciate if you could give some advice.

Answer

You can us the following comprehension:

unfiltered = ['Cat,Dog,Cow', '', 'Horse,Whale', 'Fish,Giant Elephant']
wtc = {'Whale': 'Big Whale', 'Fish': 'Jellyfish'}

result = [','.join(wtc.get(s, s) for s in e.split(',')) for e in unfiltered]
# ['Cat,Dog,Cow', '', 'Horse,Big Whale', 'Jellyfish,Giant Elephant']

This makes use of the dict.get(key, default) method. You split the list elements, apply the conversion and join the tokens back together.



Source: stackoverflow