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

Why isn't sorted() working when I try to sort the values in my dictionary?

I have a dictionary article_counter = {"Title1": {'C': 2, 'B': 1, 'A': 2}} and I’m trying to sort the counter so it becomes {"Title1": {'A': 2, 'C': 2, 'B': 1}}

I tried using this, but the values weren’t getting sorted

sorted_dict = dict(sorted(article_counter.items(), key=lambda x: (x[1][1], x[1][0])), reverse=True)

but when I do this it works just fine

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

for i in article_counter.items():
    sorted_dict[i[0]] = sorted(i[1], key=lambda x: (x[1], x[0]), reverse=True)

>Solution :

Your slicing was incorrect, reverse=True in the wrong position

article_counter = {'C': 2, 'B': 1, 'A': 2}


sorted_dict = dict(sorted(article_counter.items(), key=lambda x: (-x[1], x[0])))

Output: {'A': 2, 'C': 2, 'B': 1}

in a nested dictionary

article_counter = {"Title1": {'C': 2, 'B': 1, 'A': 2}}

sorted_dict = {k: dict(sorted(d.items(), key=lambda x: (-x[1], x[0])))
               for k, d in article_counter.items()}

Output: {'Title1': {'A': 2, 'C': 2, 'B': 1}}

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