0

So I have a JSON file that looks like this:

{
  "PlayerA": {
    "val": 200,
    "level": 1
  },
  "PlayerB": {
    "val": 1000,
    "level": 1
  },
  "PlayerC": {
    "val": 30,
    "level": 1
  }
}

And I want it to be sorted by "val," so that it looks like this:

{
  "PlayerB": {
    "val": 1000,
    "level": 1
  },
  "PlayerA": {
    "val": 200,
    "level": 1
  },
  "PlayerC": {
    "val": 30,
    "level": 1
  }
}

How would I go about doing this?

Mottly24
  • 25
  • 4
  • I think it's related to https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value – anlgrses Aug 07 '20 at 21:50
  • Convert the dictionary to an `OrderedDict`. Then see https://stackoverflow.com/questions/26533666/python-sorting-an-ordered-dictionary – Barmar Aug 07 '20 at 21:51
  • JSON is irrelevant. After you load it, it's just a dictionary, it doesn't matter where it came from. – Barmar Aug 07 '20 at 21:51
  • While you can order the objects for readability, a JSON object has no technical order within its keys. It is a sequence of unordered key / value pairs. – Klaus D. Aug 07 '20 at 21:56

1 Answers1

1

Try this:

data = {
  "PlayerA": {
    "val": 200,
    "level": 1
  },
  "PlayerB": {
    "val": 1000,
    "level": 1
  },
  "PlayerC": {
    "val": 30,
    "level": 1
  }
}

data = sorted(data.items(), key=lambda x: x[1]["val"], reverse=True)

print(data)
# [('PlayerB', {'val': 1000, 'level': 1}), ('PlayerA', {'val': 200, 'level': 1}), ('PlayerC', {'val': 30, 'level': 1})]
MisterNox
  • 1,445
  • 2
  • 8
  • 22