Reputation: 80
I have two json files, each in the form of a dictionary. I would like to compare them but ignore the 'ver' key when doing so. I've looked at the following question and implemented the answer as my function: Compare dictionaries ignoring specific keys
However, the function is still returning false when comparing two files that only have a difference in the 'ver' key.
def compare_json(file_1, file_2, ignore_key):
ignored = set(ignore_key)
for k1, v1 in file_1.iteritems():
if k1 not in ignored and (k1 not in file_2 or file_2[k1] != v1):
return False
for k2, v2 in file_2.iteritems():
if k2 not in ignored and k2 not in file_1:
return False
return True
if not compare_json(data, latest_file, ('ver')):
print 'not equal'
data['ver'] += 1
ver_number = data['ver']
with open(('json/{0}.v{1}.json').format(name, ver_number)) as new_json:
json.dump(data, new_json)
else:
print 'equal'
Here is what printing the json dicts look like:
{'ver': 1, 'data': 0}
{'ver': 2, 'data': 0}
Comparing the above should return true; however, it returns false. When I change the version numbers to the same number, it returns true.
Upvotes: 1
Views: 1957
Reputation: 57033
Change ('ver')
to ('ver',)
.
('ver')
is not a tuple, it is simply 'ver'
in the parentheses. Respectively, set(('ver'))
is {'e','r','v'}
, which are the keys that your function ignores - but they are not the keys that you want to ignore.
On the contrary, ('ver',)
is a one-element tuple, and set(('ver',))
is {'ver'}
.
Upvotes: 2