I have a dictionary such as:
d = {'a':'a-val', 'b':'b-val', 'c':'c-long-val'*1000}
And I need to repeatedly access d['c'] as in:
print('value of c is', d['c'])
x_queue.put(d['c'])
some_function(d['c'])
But I'm wondering if it would be faster to assign d['c'] to a variable and use it each time:
c_value = d['c']` # is this assignment "worth it"?
print('value of c is', c_value)
x_queue.put(c_value)
some_function(c_value)
My hunch is it may depend on
d (finding key is more costly with bigger d)d['c'] (assignment is more costly with bigger d['c'])But I'm really not sure if one of those options (or another?) is faster or more pythonic.
Although accessing a dict value by key has an average time complexity of O(1), it has a worst-case time complexity of O(n) after incurring the overhead of calculating the hash value of the key. A variable assignment and the retrieval of its value on the other hand, take very minimal, constant time, so avoid re-evaluating a dict value by key whenever possible.
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