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

Time:09-27

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

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

CodePudding user response:

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}}

  • Related