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)
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With