I was making configuration program to help the users configurate a .json
file. One of the feature of the program was to check if the saved json
is the same as the a new json
file made by the user. If the two .json
are not the same, it will tell the user to save the .json
file that is being configurated in the program.
My first thought was to read from the .json
file every time when checking if the two .json
files are the same. It looked something like this:
# read from the saved json file
new_settings = {"key1": 1, "key2": 2, "array1": []} # json.load(open('config.json', 'r').read())
# modifying new_settings
new_settings['array1'].append('Data')
def checkIsDifferent():
# read from the saved json file
saved_settings = {"key1": 1, "key2": 2, "array1": []} # json.load(open('config.json', 'r').read())
if saved_settings == new_settings:
print('Configuration is saved')
else:
print('(*)Configuration is not saved')
I don't think constantly reading from a file will be good way to compare the "settings" in my case, so I came up with another way, by copying the saved .json
to a variable, and then use the variable to compare:
saved_settings = {"key1": 1, "key2": 2, "array1": []} # read from the saved json file
new_settings = saved_settings.copy()
# modify
new_settings['array1'].append('Data')
def checkIsDifferent():
if saved_settings == new_settings:
print('Configuration is saved')
else:
print('(*)Configuration is not saved')
The first solution went expected. It outputted "(*)Configuration is not saved" when running checkIsDifferent()
function. But when I run checkIsDifferent()
on the second solution it outputted "Configuration is saved".
Is dict.copy()
in python broken? How can I fix it for the second solution?
System Environment:
Python version: Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:43:08) [MSC v.1926 32 bit (Intel)]
OS: Windows 10