Search code examples
pythondictionarykeyerror

Dict KeyError arise in for loop but actually no error


While I have a list of dictionaries detected_intersections, which has 236 items. With code:

for i in detected_intersections:
    print(i)

it looks like:

sample image

with code:

detected_intersections = detect_intersections()
for i in detected_intersections:
    if 'seq' in i:
       print(i)

it looks the same with above:

sample image

But when I use del statement or pop() method to remove key seq in a for loop, KeyError would arise:

sample image

sample image

If using code:

for i in detected_intersections:
    if 'seq' in i:
        i.pop('seq')
        print(i)

Codes would be compiled successfully, but data lose:

sample image

I am quite sure about that there is seq in every items of list and their case are correct, I am confused that why it happened.

Thank you


Solution

  • If one one the dict does not have a seq key, you will have the KeyError. You can prevent this by giving a default return value to pop():

    i.pop("seq", None)