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.