I would like to know whether there is a more efficient way of replacing a particular value in a dictionary. By "more efficient" I mean to avoid looking up the same key twice. I don't expect it would make a big difference, but I find myself doing the following alot:
foo = {'a': 0, 'b': 1}
foo['b'] = bar(foo['b'])
Update
I think the assignment above is "looking up the same key twice" because the following prints "Hashing b" three times.
class LoudKey:
def __init__(self, key):
self.key = key
def __hash__(self):
print(f'Hashing {self.key}')
return self.key.__hash__()
b = LoudKey('b')
foo = {'a': 0, b: 1}
# first "Hashing b"
foo[b] = float(foo[b])
# next two "Hashing b"s
If dict.__getitem__
and dict.__setitem__
are really not duplicating effort somehow, an elaboration on that would also be accepted as an answer.