Reputation: 1010
So I saw this question that indicates that comparing two dictionaries with ==, Python will look through each key of two dictionaries and check if each value is the same. I am writing some unit tests and I want to check to make sure that some data I am pulling from a website matches some that I previously pulled in postman, and saved to a text file. Why does comparing the dictionaries below return false, but returning those same dictionaries as sets, return true?
records = self.get_raw_records(form_id) #this pulls the data
with open("Sample Pull Data.txt", "r") as file:
contents = json.load(file) #this is the data I already pulled
print(contents[0]==records[0]) #false
print(set(contents[0]) == set(records[0])) #true
file.close()
I noticed that the order of keys varied, but accoriding to the linked question, or more importantly from the 3.6 docs: that shouldn't matter.
Mappings (instances of dict) compare equal if and only if they have equal (key, value) pairs. Equality comparison of the keys and values enforces reflexivity.
Upvotes: 1
Views: 60
Reputation: 11060
The set
only contains the keys from the dictionary - not the keys and values. As the docs say, dict comparison tests if they have equal (key, value) pairs.
So doing set
comparison is equivalent to doing dict.keys()
comparison (and in fact keys()
can be used as sets in python 3).
a = {1:1}
b = {1:2}
a == b
# False
set(a) == set(b)
# True
a.keys() == b.keys()
# True
set(a) == a.keys()
# True
Upvotes: 1