pythoncsvdictionary

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

  • 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 dictionary's "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 aren't adding empty 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)