python – Comparing two dictionaries and checking how many (key, value) pairs are equal

python – Comparing two dictionaries and checking how many (key, value) pairs are equal

If you want to know how many values match in both the dictionaries, you should have said that 🙂

Maybe something like this:

shared_items = {k: x[k] for k in x if k in y and x[k] == y[k]}
print len(shared_items)

What you want to do is simply x==y

What you do is not a good idea, because the items in a dictionary are not supposed to have any order. You might be comparing [(a,1),(b,1)] with [(b,1), (a,1)] (same dictionaries, different order).

For example, see this:

>>> x = dict(a=2, b=2,c=3, d=4)
>>> x
{a: 2, c: 3, b: 2, d: 4}
>>> y = dict(b=2,c=3, d=4)
>>> y
{c: 3, b: 2, d: 4}
>>> zip(x.iteritems(), y.iteritems())
[((a, 2), (c, 3)), ((c, 3), (b, 2)), ((b, 2), (d, 4))]

The difference is only one item, but your algorithm will see that all items are different

python – Comparing two dictionaries and checking how many (key, value) pairs are equal

def dict_compare(d1, d2):
    d1_keys = set(d1.keys())
    d2_keys = set(d2.keys())
    shared_keys = d1_keys.intersection(d2_keys)
    added = d1_keys - d2_keys
    removed = d2_keys - d1_keys
    modified = {o : (d1[o], d2[o]) for o in shared_keys if d1[o] != d2[o]}
    same = set(o for o in shared_keys if d1[o] == d2[o])
    return added, removed, modified, same

x = dict(a=1, b=2)
y = dict(a=2, b=2)
added, removed, modified, same = dict_compare(x, y)

Leave a Reply

Your email address will not be published. Required fields are marked *