Tsagana Nokhaeva
Tsagana Nokhaeva

Reputation: 815

Access dictionary several times or store in temporary variable

Say, I need to use some value from Python dictionary several times in one piece of code. What are the best practices?

Access dictionary once, store value in some temporary variable and use this variable:

value = d['my_key']

do_some_work(value)
do_some_other_work(value)
and_again(value)

or access dictionary everytime a need this value:

do_some_work(d['my_key'])
do_some_other_work(d['my_key'])
and_again(d['my_key'])

Upvotes: 0

Views: 599

Answers (2)

Elrond
Elrond

Reputation: 2112

The first approach leads to more readable functions when called, in particular when the key of the dictionary is long or not self explanatory. However, the reader will always have to check the origin of the variable if he's not willing to blindly trust the name of the variable. So why not calling the dictionary directly then?

Personally, I use both approaches according to the use case. If the key or dictionary names are long or not sufficiently self-explanatory, I create a temporary variable. Otherwise, I access the dictionary directly when calling the functions.

Upvotes: 1

Daniele Bacarella
Daniele Bacarella

Reputation: 464

For a dict, the average time complexity of accessing an item is constant O(1), see Python Time Complexity.

So, I wouldn't expect much difference in performance.

Upvotes: 1

Related Questions