'json.dump records exactly two copies of dict items

I am trying to have a dict stored in a json file, to be read and edited every time my script is run. I have found that json.dump leaves the first copy of the edited key-value and appends the second, but when run again the original key-value is removed and the first replacement is retained along with the new key-value. For example, if file.json is initially set to {} and we have code like this:

import json
with open('file.json') as file:
    data = json.load(file)
data[0] = 1
with open('file.json', 'w') as file:
    json.dump(data, file)

The first time through file.json will be {'0':1}, the second time it will be {'0':1, '0':1}, and so too the third and fourth times.



Solution 1:[1]

The problem was that I was accessing the new data with a numeric key, but json always stores the key as a string. Because of that, the new data[0] is not the same as data['0'] taken from json.load, and data becomes {'0':1, 0:1}. json.dump is happy with that two-item dict, and puts it in the json file. But there it converts the numeric key to a string, and it doesn't do like python to overwrite the first item with that identical key. When the dict is loaded the next time the script is run, python finds a duplicate key, and the first value is overwritten, so at that point data is {'0':1}, ready to accept an added key-value {0:1}.

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 Mordechai