Home > Software design >  Need to convert a list into set, but It needs to stay in alphabetical order
Need to convert a list into set, but It needs to stay in alphabetical order

Time:11-16

THis is how my code looks like:

site1 = ["breakfast", "view", "beach", "hospitality", "breakfast", "clean", "view"]
site2 = ["dinner", "view", "unfriendly", "pool", "clean", "pool"]


 site1_no_dupes = []
    for i in site1:
        if i not in site1_no_dupes:
            site1_no_dupes.append(i)
    site2_no_dupes = []
    for i in site2:
        if i not in site2_no_dupes:
            site2_no_dupes.append(i)
    my_final_list = site1_no_dupes   site2_no_dupes
    actual_final_list = []
    for i in my_final_list:
        if i not in actual_final_list:
            actual_final_list.append(i)
    actual_final_list2 = sorted(actual_final_list)
    actual_final_list3 = set(actual_final_list2)
    
    print(actual_final_list3)

When I print it it comes out likes this

{'pool', 'unfriendly', 'breakfast', 'hospitality', 'clean', 'view', 'beach', 'dinner'}

But I want it like this:

{'beach', 'breakfast', 'clean', 'dinner', 'hospitality', 'pool', 'unfriendly','view'}

I am very close because if I remove the last line it comes out like this:

['beach', 'breakfast', 'clean', 'dinner', 'hospitality', 'pool', 'unfriendly', 'view']

So the only thing I need to do here is convert it to a set while keeping it in alphabetical order, anyone know what to do? Thanks in advance!

CodePudding user response:

You can do it just in one line by first sorting the list, and turning this into a set like this:

actual_final_list2 = set(sorted(actual_final_list))
print(actual_final_list2)

your output will be:

{'beach', 'clean', 'unfriendly', 'view', 'breakfast', 'hospitality', 'dinner', 'pool'}
  • Related