Andrius Dalgeda
Andrius Dalgeda

Reputation: 39

How do you order JSON data - order returned results from lowest to highest

for val in online_json["payload"]["orders"]:
    if val["user"]["status"] == "ingame" and val["order_type"] == "sell":
        username = str(val["user"]["ingame_name"])
        quantity = int(val["quantity"])
        game_price = int(val["gameprice"])

        print(username + ' is selling ' + str(quantity) + ' for ' + str(game_price) + '  each.')

Currently the result of the query is in whatever order the API returns which leads to a lot of clutter, I would like to order the results from the lowest game_price to highest to easily display the lowest price alongside the rest of the information.

Upvotes: 1

Views: 149

Answers (1)

azro
azro

Reputation: 54168

Just use sorted and appropriate key which'll be lambda x:int(x['gameprice']). Also you can simplify your print instead of using concatenation, use multiple params

for val in sorted(online_json["payload"]["orders"], key=lambda x:int(x['gameprice'])):
    if val["user"]["status"] == "ingame" and val["order_type"] == "sell":
        username = str(val["user"]["ingame_name"])
        quantity = int(val["quantity"])
        game_price = int(val["gameprice"])

        print(username, 'is selling', quantity, 'for', game_price, 'each.')

Upvotes: 2

Related Questions