Avoiding KeyError when iterating over a list of dictionaries

Viewed 5037

I have a list of dictionaries:

test = [{'first': '1'}, {'second': '2'}, {'first': '0'}, {'third': '3'}, {'fourth': '4'}]

but when I do:

stuff = [L['first'] for L in test]
print(stuff)

I get this:

Traceback (most recent call last):
  File "C:/Users/User/Desktop/test_run.py", line 4, in <module>
    stuff = [L['first'] for L in test]
  File "C:/Users/User/Desktop/test_run.py", line 4, in <listcomp>
    stuff = [L['first'] for L in test]
KeyError: 'first'

I know I might be doing a silly mistake but any help?

4 Answers
Related