Break
Break

Reputation: 342

Reading a json and sending it after sorting Discord.py

I'm having trouble figuring out how to sort a read only json.

[
  {
    "number": "10",
    "player": "718325003376132117",
    "level": "90",
    "stats": null
  },
  {
    "number": "20",
    "player": "718325003376132117",
    "level": "99",
    "stats": "2,3,6,3.5,2"
  },
  {
    "number": "26",
    "player": "718325003376132117",
    "level": "60",
    "stats": "8,4,4,12,2"
  }
]

That is an example of the contents of the json. This is what I normally do to read it:

search = f"https://www.privatelink"

        async with aiohttp.ClientSession() as cs:
            async with cs.get(search) as r:
                Fighters = json.loads(await r.text())

And this will let me display the Fighters in top to bottom as its shown there, which is ordered by the 'number'. What I want to do is order the results by the sum of their 'stats' instead, if they aren't null. How can I do this?

Upvotes: 0

Views: 179

Answers (2)

Haider Ali Punjabi
Haider Ali Punjabi

Reputation: 355

sorted = [x for x in sorted(Fighters,key=lambda item: sum([float(y) for y in item['stats'].split(',')]) if item['stats'] else 0)]

Upvotes: 1

Alberto
Alberto

Reputation: 605

This is not related to being async or not. To sort you first get the list of items in the json, then you sort by a key your list. x or "" is meant for the null strings.

Hence, assuming fighters is the name of your list:

sorted(fighters, key=lambda x: (x["stats"] or ""))                      


# yields:
[{'number': '10',
  'player': '718325003376132117',
  'level': '90',
  'stats': None},
 {'number': '20',
  'player': '718325003376132117',
  'level': '99',
  'stats': '2,3,6,3.5,2'},
 {'number': '26',
  'player': '718325003376132117',
  'level': '60',
  'stats': '8,4,4,12,2'}]

Notice however that sorting strings might not make much sense in your case, as stats is a list of numbers separated by commas, and strings are compared alphabetically character by character (known as lexicographic order).

You might want to use instead:

sort_fn = lambda x: [ float(stat) for stat in x.split(",") ] if x or []

as Python is quite smart and will sort lists of numbers, by sorting first by the same number.

If the stats come in no particular order, meaning the first stat is not the most importatn, maybe it makes more sense to sum those numbers instead:

    sort_fn = lambda x: sum([ float(stat) for stat in x.split(",") ]) if x or []

Upvotes: 1

Related Questions