Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

I keep on getting a KeyError in Python

I keep on getting a KeyError and not sure what I’m doing wrong here??

    import csv
    
    list_of_email_addresses = []
    with open("users.csv", newline="") as users_csv:
      user_reader = csv.DictReader(users_csv)
      for row in user_reader:
        list_of_email_addresses.append(row["Email"])

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Key error means the dictionary you are trying to access does not have the key you are using to get a value from it. It looks like you are trying to access the row dictionaries "Email" key. Your csv file does not have an "Email" column in some rows and thus is giving you this error. To solve, you can do row.get("Email","") which will just return an empty string if there is no email.

You can also just do a check before you append so that you arent adding empy items to your list by doing

  for row in user_reader:
    email = row.get("Email")
    if email is None: continue
    list_of_email_addresses.append(email)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading