Skip to content
Advertisement

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.

Advertisement

Answer

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)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement