-1

I have a list of dictionaries and trying to sort by key but couldn't get met requirement. I'm new to python. I have tried the following solution

sorted(data, key=itemgetter('key'))
data = [
          {
            "key" : "NEU",
            "value" : 49
          },
          {
            "key" : "POS",
            "value" : 30
          },
          {
            "key" : "NEG",
            "value" : 39
          },
          {
            "key" : "N/A",
            "value" : 10
          }
        ]

I want output like

[         {
            "key" : "N/A",
            "value" : 10
          },
          {
            "key" : "NEG",
            "value" : 39
          },
          {
            "key" : "NEU",
            "value" : 49
          },
          {
            "key" : "POS",
            "value" : 30
          }
        ]
M Usman Wahab
  • 53
  • 1
  • 10
  • 2
    Does this answer your question? [How do I sort a list of dictionaries by a value of the dictionary?](https://stackoverflow.com/questions/72899/how-do-i-sort-a-list-of-dictionaries-by-a-value-of-the-dictionary) – ProGamer May 12 '20 at 12:16

1 Answers1

0

I think you're looking for this:

sorted(data, key=lambda x: x["key"])

We create an anonymous function via lambda where our argument is x (the values inside of data) and then we return the entry key of the dictionary inside of the lists to sort the data.

Hampus Larsson
  • 3,050
  • 2
  • 14
  • 20