1

I wanted to dump a dictionary into a json file, and later on, load it so then I would use it.

dic = {}

for n in range(1,10):
    if n%2==0:
        dic[n] = n**2
    else:
        dic[str(n)] = n**2
print(dic)

The printed output is :

{'1': 1, 2: 4, '3': 9, 4: 16, '5': 25, 6: 36, '7': 49, 8: 64, '9': 81}

It's the result that i wanted But when I json.dump it and json.load it,...

with open("myfile.json","w") as fp:
    json.dump(dic,fp)
with open("myfile.json") as fq:
    newdic=json.load(fq)

print(newdic)

The output is :

{'1': 1, '2': 4, '3': 9, '4': 16, '5': 25, '6': 36, '7': 49, '8': 64, '9': 81}

All the keys become string. In this simple case it's avoidable, But what should I do in complicated cases?

Any help appreciated.

mahisafa82
  • 11
  • 1
  • 3
    Does this answer your question? [Python's json module, converts int dictionary keys to strings](https://stackoverflow.com/questions/1450957/pythons-json-module-converts-int-dictionary-keys-to-strings) – Dhaval Taunk Jun 05 '20 at 14:13
  • 2
    I'm not sure what exactly is the question, or what is the output that you want to get. As you said, since JSON only allows strings as object keys, you will not be able to avoid getting strings when parsing the document. Are you looking for something to work around this fact? What do you mean by "complicated cases"? You can use [`pickle`](https://docs.python.org/3/library/pickle.html) as an alternative. – jdehesa Jun 05 '20 at 14:14
  • Why are you using a dict instead of a list and what are the "complicated cases" ? – ludel Jun 05 '20 at 14:15

3 Answers3

2

The JSON spec requires all the keys to be strings. This is not true in Python, where objects which are not strings can be keys in a dictionary.

Riccardo Bucco
  • 13,980
  • 4
  • 22
  • 50
1

In JSON, keys must be strings.

So, once you have dumped your dictionary as JSON, there is no way to return it as it is when you load it again. This kind of information is no longer known.

You can check this question for the other complicated cases if you need. It is about using pickle instead of JSON: https://stackoverflow.com/a/17328255/8528141

Yasser Mohsen
  • 1,411
  • 1
  • 12
  • 29
0

As other answers suggest that, it is true that JSON requires all the keys to be string only. So if you store the dict in to JSON format then all your keys become string and upon loading the dict back you get the keys in string.

If you want to store and load the dict in same format then you can either save the key_type along with the dict or you can consider the pickle library which stores and loads the Python Data Structure without changing anything in that.

HNMN3
  • 542
  • 3
  • 9