I want to compare dictionaries with Python to verify equivalence.

Asked 2 years ago, Updated 2 years ago, 22 views

Is it okay to use == to compare the two dictionaries in python?
I'd like to see if all key,value pairs match.

dict1={'a':1,'b':2,'c':3}
dict2 = {'a':1,'c':3,'b':2}
print(dict1==dict2)

dict3 = {'a':1,'b':2,'c':3}
dict4 = {'a': 1, 'c': 3, 'b': 2.0}
print(dict3==dict4)

Both prints returned True.
I understand that the order of keys does not matter in the dictionary.
There is no problem that 2==2.0 is determined by True.

In the example, the key is a string and the value is a number, but is it okay if the value is a list or a dictionary?

import pickle
x = pickle.dumps (dict1)
y = pickle.dumps (dict2)
print(x==y)

p=pickle.dumps(dict3)
q = pickle.dumps (dict4)
print(p==q)

By the way, x==y became True while p==q became False when serialized with pickle.dumps().

python

2022-09-30 18:57

1 Answers

Is there no problem if the value is a list or a dictionary?

The recursive comparison of lists/dictionaries results in expected behavior.

From Python (3.6) The Python Language Reference 6.10.1.Value comparisons:

The following list descriptions the comparison behavior of the most important building-intypes.

  • [...]
  • Sequences (instances of tuple, list, or range) can be shared only with each of the types, with the restriction that does not support order comparison.Equality comparison across these processes and requirements
  • [...]
  • Mappings(instances of dict)compare equal if and only if they have equal (key, value)pairs.Equality comparison of the keys and elements reflexibility.

Serialization with pickle.dumps() resulted in x==y being True and p==q being False.

As you can see from the serialization results, 2 and 2.0 parts have been converted to different byte strings. p, q are not equivalent because they are different byte strings (p==q results are False).

Also, x==y became True by accident.Other Python processing systems may have different results.When I tried it on hand, the results were different for CPython 3.6 and 3.5.This may be because CPython 3.6 implemented a modified dictionary type (dict) to keep the order, but Python still "does not guarantee dictionary type order."


2022-09-30 18:57

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.