Reputation: 3218
When I wish to both retrieve and replace a value in a dict, I naively write:
old_value = my_dict['key']
my_dict['key'] = new_value
But.. that's two lookups for 'key'
in my_dict
hashtable. And I'm sure that only one is necessary.
How do I get the same behaviour with only one lookup?
Does python automately JIT-optimizes this away?
[EDIT]: I am aware that python dict lookup is cheap and that performance gain would be quite anecdotic unless my_dict
is huge or the operation is done billions times a milisecond.
I am just curious about this apparently-basic feature being implemented or not in python, like an old_value = my_dict.retrieve_and_replace('key', new_value)
.
Upvotes: 2
Views: 96
Reputation: 16941
Storing a reference rather than a value in the dict will do what you want. This isn't intended to be an elegant demonstration, just a simple one:
>>> class MyMutableObject(object):
pass
>>> m = MyMutableObject()
>>> m.value = "old_value"
>>> my_dict["k"] = m
Now when you want to change my_dict["k"]
to a new value but remember the old one, with a single lookup on "k"
:
>>> m2 = my_dict["k"]
>>> m2.value
'old_value'
>>> m2.value = 'new_value'
It's up to you to decide if the price this pays in complexity is worth the time saving of one dictionary lookup. Dereferencing m2.value
and assigning it afresh will cost 2 more dictionary lookups under the hood.
Upvotes: 1