Is there a way to either insert a new key into a dict
or fail if that key already exists without hashing twice?
From something like this:
class MyClass:
def __init__(self):
pass
def __hash__(self):
print('MyClass.__hash__ called')
return object.__hash__(self)
my_key = MyClass()
my_value = "my_string"
my_dict = {}
if my_key not in my_dict:
my_dict[my_key] = my_value
else:
raise ValueError
you can see that __hash__
is called twice and this code doesn't express the desired behavior of insertion or failure as an atomic operation.
my_dict.setdefault(my_key, my_value)
setdefault(key[, default])
If key is in the dictionary, return its value. If not, insert key with a value of default and return default. default defaults toNone
.
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