Can I change the way keys are compared in a Python dict? I want to use the operator 'is' instead of ==
14:05 16 Jun 2017

Let's say I have two objects of a same class: objA and objB. Their relationship is the following:

(objA == objB)    #true
(objA is objB)    #false

If I use both objects as keys in a Python dict, then they will be considered as the same key, and overwrite each other. Is there a way to override the dict comparator to use the is comparison instead of == so that the two objects will be seen as different keys in the dict?

Maybe I can override the equals method in the class or something? To be more specific, I am talking about two Tag objects from the BeautifulSoup4 library.

Here's a more specific example of what I am talking about:

from bs4 import BeautifulSoup

HTML_string = "

some_header

some_header

" HTML_soup = BeautifulSoup(HTML_string, 'lxml') first_h1 = HTML_soup.find_all('h1')[0] #first_h1 =

some_header

second_h1 = HTML_soup.find_all('h1')[1] #second_h1 =

some_header

print(first_h1 == second_h1) # this prints True print(first_h1 is second_h1) # this prints False my_dict = {} my_dict[first_h1] = 1 my_dict[second_h1] = 1 print(len(my_dict)) # my dict has only 1 entry! # I want to have 2 entries in my_dict: one for key 'first_h1', one for key 'second_h1'.
python dictionary beautifulsoup equality