How to sort the list "by value" inside the given list of dicts in Python 3 dict ?

Submitted 3 years, 4 months ago
Ticket #310
Views 268
Language/Framework Python
Priority Low
Status Closed

Is there any simpler way to do ??

Submitted on Nov 30, 20
add a comment

1 Answer

Verified

Does this topic solve your question?

Here is the problem presented there and the accepted answer:

Is there a simple way to sort the following Python d:dict by value of key '#1'. The output should be as shown in o:dict ? I want to be able to print in different kind of orders like a html tabel with asc/desc key. I know how to sort a simple key:value with the sorted() but cant figure out how to do it, when the value is as shown below !! I'm using CPython 3.9

d:dict = {  'aaa': {'#1': 9,  '#2':34,  '#3': 5},
            'bbb': {'#1': 11, '#2': 15, '#3': 7},
            'ccc': {'#1': 6,  '#2': 3,  '#3': 6} }

o:dict = {  'ccc': {'#1': 6,  '#2': 3,  '#3': 6},
            'aaa': {'#1': 9,  '#2': 34,  '#3': 5},
            'bbb': {'#1': 11, '#2': 15, '#3': 7}   }

And this is the accepted answer:
d = {  'aaa': {'#1': 9,  '#2':34,  '#3': 5},
       'bbb': {'#1': 11, '#2': 15, '#3': 7},
       'ccc': {'#1': 6,  '#2': 3,  '#3': 6} }

o = dict(sorted(d.items(), key=lambda x: x[1]["#1"]))

Submitted 3 years, 4 months ago


Latest Blogs