1

I would like for the loop to keep going even exception is generated at first iteration. How to do this?

mydict = {}
wl = ["test", "test1", "test2"]
    
try:
  for i in wl:
   a = mydict['sdf']
   print(i)
            
except:
       # I want the loop to continue and print all elements of list, instead of exiting it after exception
       # exception will occur because mydict doesn't have 'sdf' key
    pass
Akshat Zala
  • 710
  • 1
  • 8
  • 23
electro
  • 911
  • 4
  • 12
  • 28

3 Answers3

1

You can use dict.get(). It will return None if the key not exist. You can also specify default value in dict.get(key, default_value)

for i in wl:
    a = mydict.get('sdf')
    print(i)
deadshot
  • 8,881
  • 4
  • 20
  • 39
0

The best I can advice is to move the try inside the loop as below:

mydict = {}
wl = ["test", "test1", "test2"]
for i in wl:
    try:
        a = mydict['sdf']
        print(i)

    except:
        continue
Albert Alberto
  • 801
  • 8
  • 15
0

This is my approach for your problem
Hope its work for you as you want

mydict = {}
wl = ["test", "test1", "test2"]

for i in wl:
    try:
        a = mydict['sdf']
    except:
        pass
    print(i)
Amirul Akmal
  • 401
  • 6
  • 13