Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I specify custom comparator for the "in" keyword in Python?

I am fairly new to Python, so I welcome alternative approaches.

I have a list of dictionaries that I start with (read from a file). Now I have a bunch of additional dictionaries that I'd like to add to this list, but only if they are not in the original list.

However, I require that "not in the original list" is defined by a custom comparison function, rather than whatever Python uses as default.

More specifically, I want to compare certain key/value pairs in the dictionary, and if they are the same, return "true" for the expression.

myList = ReadFromFile...
newList = ReadFromFile...
for item in newList:
    if item not in myList: #I want custom behavior for this "in"
        myList.append(item)
like image 925
merlin2011 Avatar asked Dec 13 '22 03:12

merlin2011


2 Answers

Use any:

any(customEquals(item, li) for li in myList)

If myClass is of a type that you can control, you can also overwrite the __contains__ method.

like image 93
phihag Avatar answered Dec 29 '22 00:12

phihag


You don't. The in operator is part of the language syntax. What you want to do is something like this:

def comparison(item, otherContainer):
  # Code here for custom comparison.
  return True or False

for item in NewList:
  if not comparison(item, myList):
    myList.append(item)
like image 34
g.d.d.c Avatar answered Dec 28 '22 23:12

g.d.d.c