There are two dicts: old and updated. I wanna to check if they are equal, except status
, latitude
and longitude
keys.
assert old_dict['status'] != updated_dict['status']
assert old_dict['latitude'] != updated_dict['latitude']
assert old_dict['longitude'] != updated_dict['longitude']
for field in ('status', 'latitude', 'longitude'):
updated_dict.pop(field)
old_dict.pop(field)
assert old_dict == updated_dict
What is the more pythonic way to do this?
Use == operator to check if the dictionaries are equal It will return True the dictionaries are equals and False if not. Created four dictionaries(dict1, dict2, dict3, dict4) using different methods. Using dict1 == dict2 == dict3 == dict4 code syntax we are comparing all the dictionaries.
For simple dictionaries, comparing them is usually straightforward. You can use the == operator, and it will work.
Use the == Operator to Compare Two Dictionaries in Python The == operator in Python can be used to determine if the dictionaries are identical or not.
According to the python doc, you can indeed use the == operator on dictionaries.
A bit of an unorthodox suggestion, but hear me out:
differing = {"status", "latitude", "longitude"}
assert all(
(old_dict[key] != updated_dict[key]) == (key in differing)
for key in old_dict
)
For every key
, we assert that the values differ if and only if the key is one of the differing keys.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With