Home > Enterprise >  How would I sort this json based off of each id's score value using Python?
How would I sort this json based off of each id's score value using Python?

Time:11-20

I'm trying to put these ID's in order based off of each ones score value, highest being on the top and lowest being on the bottom

{
  "Users": {
    "586393728470745123": {
      "score": 150, 
      "name": "user1"
    }, 
    "437465122378874895": {
      "score": 115, 
      "name": "user2"
    }, 
    "904032786854346795": {
      "score": 65, 
      "name": "user3"
    }, 
    "397930609894490122": {
      "score": 810, 
      "name": "user4"
    }, 
    "384814725164433408": {
      "score": 10, 
      "name": "user5"
    }, 
    "337104925387390977": {
      "score": 1, 
      "name": "user6"
    }, 
    "243452651541495808": {
      "score": 10, 
      "name": "user7"}
  }
}

I tried using pythons sorted() function but couldn't figure it out myself

CodePudding user response:

Well, i don't know what data structure you want to get, but in Python, dicts do not have no particular order of keys. So, if having a list of user id's, sorted by their score, try something like this (Scores is the dict you posted):

sorted(list(Scores["Users"]),key= lambda x: Scores["Users"][x]["score"])

Also, notice, that the first id is the one with the lowest score. If you want it the other way round, add reverse = True after the lambda.

  • Related