Similar items

The following code is efficient if you're processing many similar items, but it's harder to read:

for key in mylist:

if key in cache:

result.append(cache[key]) else:

# Add to cache and append to result result.append(cache.setdefault(key, getValue(key)))

Tip If you think that the keys will almost always be in the dict, the following is even more efficient. That's because try blocks take very little time if an exception isn't raised, but exceptions take a lot of time to process:

result.append(cache[key]) except KeyError:

# Add to cache and append to result result.append(cache.setdefault(key, getValue(key)))

Was this article helpful?

0 0

Post a comment