V
V
Vlad Tanashchuk2020-06-23 18:44:38
Python
Vlad Tanashchuk, 2020-06-23 18:44:38

How can you convert a dictionary key to an int?

Hello, there is a small script for uploading data from a JSON file.
It works great and loads the information I need into the dictionary, but the fact is that in the dictionary the value of the key should be int, but it turns out something like this (the keys marked with an arrow are my problem):
5ef222d58422c405940124.png
Script for adding data:

with open('data.json', 'w', encoding='utf-8') as fh:
    fh.write(json.dumps(data, sort_keys=True, indent=4, ensure_ascii=False))

Data loading script:
with open('data.json', 'r', encoding='utf-8') as fh:
       data = json.load(fh)
       for key, value in data.items():
           data[int(key)] = value

Answer the question

In order to leave comments, you need to log in

2 answer(s)
S
soremix, 2020-06-23
@SoreMix

Json.dupm() translates keys to str

D
Dr. Bacon, 2020-06-23
@bacon

This is a feature of js, since json is part of it. Possible solutions:
1. If it then goes to js, ​​then use all the same strings or refuse such keys.
2. If only in python, then write your own object_hook or use another format for serialization.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question