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

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)

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

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

names_to_sort = sorted(names_to_sort)

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