Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Insert into dictionary or fail if key already present without hashing twice

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.

like image 465
Praxeolitic Avatar asked Dec 19 '22 19:12

Praxeolitic


1 Answers

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 to None.

like image 149
deceze Avatar answered Dec 21 '22 09:12

deceze