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

convert a list of pairs with a fixed suffix to a dictionary

I have a big list like the below one:

my_list = ['name1', 'name2', 'sth1', 'sth2', 'sth2_suffix', 'sth1_suffix', 'name2_suffix', 'name1_suffix']

and I want to make a dictionary of it like this:

my_dict = {'name1': 'name1_suffix', 
           'name2': 'name2_suffix', 
           'sth1': 'sth1_suffix', 
           'sth2': 'sth2_suffix'}

This means there are two types of elements: regular simple ones and the other ones with a fixed suffix that I want as keys or values.

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

>Solution :

You can just "ignore" the suffix elements and add them manually as values to the original items.

From Python 3.9, you can use the removesuffix string method:

my_list = ['name1', 'name2', 'sth1', 'sth2', 'sth2_suffix', 'sth1_suffix', 'name2_suffix', 'name1_suffix']

d = {item.removesuffix("_suffix"): item + "_suffix" for item in my_list}
print(d)

For other versions, you can filter the list:

my_list = ['name1', 'name2', 'sth1', 'sth2', 'sth2_suffix', 'sth1_suffix', 'name2_suffix', 'name1_suffix']
d = {}

for item in filter(lambda s: not s.endswith("_suffix"), my_list):
    d[item] = item + "_suffix"

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