Sorting dictionaries alphabetically inside the list

I’m having trouble sorting my dictionaries in the list.

Unfortunately the sorted function doesn’t work the way I want it to.

(below is my code)

names_to_sort = [{'Karwinski', 'Bandyciak', 'Anoniasz'}, {'Aajacykowa', 'Tomaszek', 'Kochanowa'}] #sample names

names_to_sort = sorted(names_to_sort)


#expected result
# [{'Aajacykowa', 'Kochanowa', 'Tomaszek'}, {'Anoniasz', 'Bandyciak', 'Karwinski', } ]

Dictionaries inside each other should be sorted alphabetically.
Additionally, dictionaries should be organized according to the first name in the dictionary. So if the first name in Dictionary 1 is 'Anonias' and the first name in Dictionary 2 is 'Aajacykowa' then the dictionaries should swap places because 'Aajacykowa' is in the alphabet before 'Anonias'.

Thank you in advance for your help

>Solution :

What you want is a lexical ordering of a list of sets (not dictionaries – those contain key-value pairs) of names by first ordering the names, then ordering the sets of names.
For this you’ll have to turn the sets into sorted lists (luckily sorted already does this for you), which may then be sorted – first sorting the names, then sorting the lists of sorted names lexicographically using sorted:

names_to_sort = sorted(map(sorted, names_to_sort))

yields the desired result (except obviously not as sets); if you want sets, simply convert the lists back to sets:

names_to_sort = list(map(set, names_to_sort))

Leave a Reply