Avoiding KeyError when iterating over a list of dictionaries
I have a list of dictionaries, and I want to get all the values which have 'first' as key. 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 want to get: ['1', '0'] I know I might be doing a silly mistake. Do I need to make an if con
0 upvotes
View original discussion ↗
Comments
Sign in or sign up to comment and upvote.
No comments yet.