Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if 2 dicts are equal except some fields?

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?

like image 439
petrush Avatar asked Oct 01 '18 11:10

petrush


People also ask

How do you know if two Dicts are equal?

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.

How do you compare Dicts?

For simple dictionaries, comparing them is usually straightforward. You can use the == operator, and it will work.

Can we compare 2 dictionaries in Python?

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.

Can == operator be used on dictionaries?

According to the python doc, you can indeed use the == operator on dictionaries.


1 Answers

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.

like image 191
L3viathan Avatar answered Oct 05 '22 23:10

L3viathan