Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to substitute a list of words based on a list of tuples by preserving the same original order?

Given the following list of tokens:

a = ['heyyo', 'how', 'ale', 'yiou']

And a list of tuples:

b = [('yiou', 'you'), ('heyyo', 'hello')]

How can I replace the elements of the list a considering the elements of the list b? For example, the expected output would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

['hello', 'how', 'ale', 'you']

This is due to list b has as a replacement:yiou for you and heyyo for hello. How to make the above replacement securing the same original order of list a?

>Solution :

You can create a dict on b and then search each item of a in dct_b with dict.get(). If exist return value base key and if doesn’t exist return the item.

dct_b = dict(b)
res = [dct_b.get(item, item) for item in a]
print(res)

Output:

['hello', 'how', 'ale', 'you']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading