0

I am comparing two dictionaries using == , which returns true in case of similar keys and corresponding values. Even reordering the dictionary results true. But I wanted to know how does it happen behind the scene. I printed the ids of the dictionary items and found that all the dictionary items with same keys or values from the two dictionaries have same ids. So does Python compares the ids from both the dictionaries?

dict1 = {'marks': 23}

for key, value in dict1.items():
    print(f'Key: {key} with id:{id(key)} :=: value:{value} with id:{id(value)}')

dict2 = {'marks': 23}

for key, value in dict2.items():
    print(f'Key: {key} with id:{id(key)} :=: value:{value} with id:{id(value)}')

dict1 == dict2

Output

Key: marks with id:4477545520 :=: value:23 with id:4456492064
Key: marks with id:4477545520 :=: value:23 with id:4456492064
True

One more question here is if I print the tuple's id then why does it print different value on each execution?

for i in range (1, 11):
    for item in dict1.items():
        print(f'{i}: item: {item} with id:{id(item)}')

Output:

1: item: ('marks', 23) with id:4546950464
2: item: ('marks', 23) with id:4546764672
3: item: ('marks', 23) with id:4546873984
4: item: ('marks', 23) with id:4547194816
5: item: ('marks', 23) with id:4546711424
6: item: ('marks', 23) with id:4547191680
7: item: ('marks', 23) with id:4546735552
8: item: ('marks', 23) with id:4546929088
9: item: ('marks', 23) with id:4546773696
10: item: ('marks', 23) with id:4546776832

CodeAdocate
  • 149
  • 1
  • 4

2 Answers2

-1

You can find the CPython implementation over here.

As you can tell from

cmp = PyObject_RichCompareBool(aval, bval, Py_EQ);

it basically does the equivalent of da[key] == db[key] for each key.

AKX
  • 152,115
  • 15
  • 115
  • 172
-1

The important thing to note, is that "is" will return True if two variables point to the same object. == will return true if the objects referred to by the variables are equal.

Refer to the implementation of python here:

https://github.com/python/cpython/blob/490c5426b1b23831d83d0c6b269858fb98450889/Objects/dictobject.c#L2844-L2892

By default, two dicts are equal if they have the same keys and values.

The best way to understand how it works is to implement equality in a class of your own. For example:

class MyClass:
    def __init__(self, foo, bar):
        self.foo = foo
        self.bar = bar

    def __eq__(self, other): 
        if not isinstance(other, MyClass):
            # don't attempt to compare against unrelated types
            return NotImplemented

        return self.foo == other.foo and self.bar == other.bar

Try implementing equality of your own class, or look at the source code of how equality is implemented for other data types you are interested in.

Please mark this answer as correct if it solves your problem.

Rahul Iyer
  • 19,924
  • 21
  • 96
  • 190