Hi in my code there is a dictionary of dictionary.
nrec={\'bridge\': \'xapi1\', \'current_operations\': {}, \'uuid\': \'9ae5ca7d-e7d6-7a81-f619-d0ea33efb534\', \
If this is a config item, you shouldn't need to access it very often (thus your efficiency requirement would be questionable). Configure once and forget about it (e.g. set self.is_guest_installer_network = True
).
If you can't forget about it, it would depend on the likelihood of the entry being present in your dictionary. If it's more likely that the item is missing it would probably be better if you do something like the following. You get some shortcut behavior if an item misses, the other config dict is looked up only once (for the existance check and for the value following lookup.
def check_guest_installer_network(nrec):
other_config = nrec.get("other_config", None)
return other_config is not None and other_config.get('is_guest_installer_network', False)
If it's more likely that the item is there, the lazy try/except approach could be better suited. As the saved check performance, would outweigh the additional performance cost when the exception actually needs to be handled.
def check_guest_installer_network(nrec):
try:
return nrec["other_config"]['is_guest_installer_network'] == "true"
except KeyError:
return False
After all, if this check indeed has a significant impact on the overall performance, you should put this variable somewhere it is better accessible, than in a nested dictionary, e.g. put it into a global/class member variable once, and enjoy the cheap and easy checks afterwards.
You should have a look at the cprofile module to verify that this lookup is indeed the bottleneck of your software, that is worth the optimization effort. And You should look at the timeit module to choose the most performant solution for your problem.