Skip to content

Instantly share code, notes, and snippets.

@nara-l
Last active August 1, 2018 14:20
Show Gist options
  • Save nara-l/d4e199c626bebcf62616170430d912a2 to your computer and use it in GitHub Desktop.
Save nara-l/d4e199c626bebcf62616170430d912a2 to your computer and use it in GitHub Desktop.
Get failed keys in Try , except python 2 and 3
# We want to get the keys which failed this could be applied to other situations
# Python 3
dict_of_elements = {1: 'john', 2: 'peter', 3: 'luke', 4: 'mark'} # can equally be a list?
failed_keys = set()
for list in dict_of_elements:
try:
dict_of_elements[9] # trying to access keys that don't exist
except Exception as e:
f_k = e.args[0]
failed_keys.add(f_k)
print (failed_keys) # # {9} because key 9 does not exist in the dictionary
# Python 2 would be something like this
dict_of_elements = {1: 'john', 2: 'peter', 3: 'luke', 4: 'mark'} # can equally be a list?
failed_keys = set()
for list in dict_of_elements:
try:
dict_of_elements[9] # trying to access keys that don't exist
except KeyError, e:
f_k = e.args[0]
failed_keys.add(f_k)
print (failed_keys) # {9} because key 9 does not exist in the dictionary
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment