'How to update json file sorted by number? - Python

For example I have a JSON file with a mess number

{
    "data": {
        "31": {
           ...

        },
        "52": {
           ...
        },
        "1": {
           ...
        }
    }
}

I wanted to make It like sorted by number so the json data will not be messed up

{
    "data": {
        "52": {
           ...

        },
        "31": {
           ...
        },
        "52": {
           ...
        }
    }
}

I tried a code that uses:

with open ("file.json", "r", encoding="utf-8") as f:
    file = json.load(f)

file["data"].update(
    {num: {"question": question, "answer": answer, "options": options}}
)

My errors code: TypeError: cannot convert dictionary update sequence element #0 to a sequence



Solution 1:[1]

Option #1

Use sorted with key argument:

import json

my_dict = {
    "data": {
        "31": {
           "k": "..."
        },
        "52": {
           "k": "..."
        },
        "1": {
           "k": "..."
        }
    }
}

my_dict['data'] = dict(sorted(my_dict['data'].items(), key=lambda t: int(t[0])))
print(my_dict['data'])

Result:

{'1': {'k': '...'}, '31': {'k': '...'}, '52': {'k': '...'}}

Option #2

Use json.dumps with sort_keys argument:

print(json.dumps(my_dict, indent=2, sort_keys=True))

Result:

{
  "data": {
    "1": {
      "k": "..."
    },
    "31": {
      "k": "..."
    },
    "52": {
      "k": "..."
    }
  }
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 rv.kvetch