Alex
Alex

Reputation: 44385

Why does a comparison of identical dict values in python 3.5.2 returns False?

In order to use the example you need to create the following json file (test.json):

{
  "/apps/media/efel_data/efel_gui/results/305933/20180515094131/u_res": {
    "step_700.0": {
      "stimuli": [
        {"delay": 620.0, "amp": 700.0, "duration": 1000.0, "totduration": 1300.0},
        {"delay": 0.0, "amp": 0.0, "duration": 1300.0, "totduration": 1300.0}
      ]
    }
  }
}

and to create a zip file containing this single file (just for demonstration purposes)

ls | zip -@ files.zip

Supposing both files are in a folder temp run the following code:

import zipfile
import json

z = zipfile.ZipFile("temp/files.zip")
with z.open('test.json') as f:
     data = json.loads(f.read().decode('utf-8'))
with open('temp/test.json') as f:
    expected = json.loads(f.read())
print(data.values())
print(expected.values())
print(data.values()==expected.values())

Now, I need to compare the values of the dict (as the first key can be different in the real code usage). However, the output of the code (python 3.5.2) indicates that the identical values are not identical:

dict_values([{'step_700.0': {'stimuli': [{'totduration': 1300.0, 'amp': 700.0, 'delay': 620.0, 'duration': 1000.0}, {'totduration': 1300.0, 'amp': 0.0, 'delay': 0.0, 'duration': 1300.0}]}}])
dict_values([{'step_700.0': {'stimuli': [{'totduration': 1300.0, 'amp': 700.0, 'delay': 620.0, 'duration': 1000.0}, {'totduration': 1300.0, 'amp': 0.0, 'delay': 0.0, 'duration': 1300.0}]}}])
False

Any explanation what is going on, and how I can fix this problem?

Upvotes: 0

Views: 42

Answers (1)

Eypros
Eypros

Reputation: 5723

Apparently your 2 dict are identical. This can be confirmed if you convert your dict.values() to list() for example:

print(list(data.values()) == list(expected.values()))

True

I think the problem is in the way python compares dict.values(). The funny thing is that even items() work correctly:

print(data.items() == expected.items())

True

You mentioned you are not interested in keys, but keys() comparison also returns True. items may also be out of the question but it's strange that it doesn't fail as in the values comparison. Anyway as a work around I would suggest converting to a list if it's not too much overhead. If there is I am not sure how you could resolve it, though.

Upvotes: 2

Related Questions