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

how to sort a Dictionary in list?

I had Question in python
Imagine a list with dictionaries in it
how can we sort it by a value in dictionary ?

Imagine this list :

lst = [
    {
        "a" : 3,
        "b" : 2
    },
    {
        "a" : 1,
        "b" : 4
    },
    {
        "a" : 2,
        "b" : 3
    }
]

how can we sort this list by value of "a" in each dictionary (python)
i mean i want this list at the end :

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

lst = [
    {
        "a" : 1,
        "b" : 4
    },
    {
        "a" : 2,
        "b" : 3
    },
    {
        "a" : 3,
        "b" : 2
    }
]

>Solution :

You could provide a lambda key to sorted:

>>> lst = [
...     {
...         "a" : 3,
...         "b" : 2
...     },
...     {
...         "a" : 1,
...         "b" : 4
...     },
...     {
...         "a" : 2,
...         "b" : 3
...     }
... ]
>>> sorted(lst, key=lambda d: d["a"])
[{'a': 1, 'b': 4}, {'a': 2, 'b': 3}, {'a': 3, 'b': 2}]
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