Skip to content

Instantly share code, notes, and snippets.

@kojiromike
Last active December 24, 2015 06:08
Show Gist options
  • Save kojiromike/6754695 to your computer and use it in GitHub Desktop.
Save kojiromike/6754695 to your computer and use it in GitHub Desktop.
Try to set a dict to true at a key only if the key already exists in the dict. Assume dict is a vanilla dict.
def setExistingKeyToTrue(addict, key):
"""Try to set a dict to True at a key only if the key already exists in the dict. Assume addict is a vanilla dict. Try to do this with only a single hash table lookup."""
try:
addict[key] = bool(addict[key]) # Fails criteria, two hash lookups
addict[key] = True # Fails criteria, always sets value
except KeyError:
pass
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment