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