Home > Back-end >  I keep on getting a KeyError in Python
I keep on getting a KeyError in Python

Time:01-18

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"])

CodePudding user response:

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)

CodePudding user response:

In python, you access a dictionary like this.

myDict = {1: "foo", 2: "bar}
print(myDict[1], myDict[2])
>>> foo, bar

I imagine your CSV file doesn't have the column you're trying to access as a key and that's why a KeyError is being raised.

  •  Tags:  
  • Related