Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python: How to ensure keys are type int

In my code, I have a nested dictionary and I want to ensure that key id is an integer (note: it is a primary key). I tried just casting it to an int but I am unsure if the key is an int given that in the JSON there are double quotes.

See below my code and example of the data format.

statistics = defaultdict(dict)

\\in a loop
statistics[state][date].append({
                        int(id): {
                            "count_targets": targets,
                            "count_targets_excluded": excluded,
                            "count_targets_pending": pending,
                            "count_targets_in_progress": progress,
                            "count_targets_completed": completed,
                            "count_targets_failed": failed
                        }
                    })


{
  "stateA": {
    "2015-02-15": [
      {
        "13": {
          "count_targets": 5,
          "count_targets_excluded": 3,
          "count_targets_pending": 3,
          "count_targets_in_progress": 0,
          "count_targets_completed": 1,
          "count_targets_failed": 0
        }
      },
      {
        "14": {
          "count_targets": 4,
          "count_targets_excluded": 3,
          "count_targets_pending": 3,
          "count_targets_in_progress": 0,
          "count_targets_completed": 1,
          "count_targets_failed": 0
        }
      },

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

JSON objects can only use JSON strings as keys:

>>> json.dumps({3: 4})
'{"3": 4}'

While the key in you dict is certainly an int, it gets converted to a string when encoding as JSON. JSON itself doesn’t have a way of "remembering" the original type of the value used as a key, so you need some method (extra data in your JSON object, a pre-defined schema, etc) that the consumer of the JSON can use to turn the key back into an int after decoding.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading