2

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 :

lst = [
    {
        "a" : 1,
        "b" : 4
    },
    {
        "a" : 2,
        "b" : 3
    },
    {
        "a" : 3,
        "b" : 2
    }
]
Peyman S87
  • 53
  • 4
  • See this question: https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary?rq=1 – Nyps Dec 15 '22 at 14:12
  • Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – alphaBetaGamma Dec 15 '22 at 14:13
  • @alphaBetaGamma your link is not the same logic – mozway Dec 15 '22 at 14:22
  • Use 'get()' method as follows: my_list = [{"a": 3, "b": 2}, {"a": 1, "b": 10}, {"a": 2, "b": 3}] k=sorted(my_list,key=lambda x :x.get('a')) print(k) – AlekhyaV - Intel Dec 16 '22 at 13:55

2 Answers2

2

One approach, use the key argument with itemgetter:

from operator import itemgetter

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

res = sorted(lst, key=itemgetter("a"))
print(res)

Output

[{'a': 1, 'b': 4}, {'a': 2, 'b': 3}, {'a': 3, 'b': 2}]

From the documentation on itemgetter:

Return a callable object that fetches item from its operand using the operand’s getitem() method. If multiple items are specified, returns a tuple of lookup values. For example:

After f = itemgetter(2), the call f(r) returns r[2].
After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3]).

Dani Mesejo
  • 61,499
  • 6
  • 49
  • 76
2

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}]
Sash Sinha
  • 18,743
  • 3
  • 23
  • 40