Paul Shearer
Paul Shearer

Reputation: 1

Zapier Code - Python KeyError when accessing input_data Key with no Value

I am using a Zapier code step to format multiple pieces of data for later use in my multi-step Zap. The curious thing about this problem is that my Code step passes the test. My suspicion is that it fails when one of the pieces of data that I am passing into the input_data dictionary has no value from the previous step. This is often the case with optional form fields which may or may not contain value.

I am getting a KeyError in my Task History logs, and subsequently Zapier keeps turning my Zap off.

Did I make a mistake? Or is this a bug in the way Zapier Code handles input_data keys that have no value?

Here is my code:

gender = input_data['gender']
renewalDate = input_data['renewalDate']
dateOfBirth = input_data['dateOfBirth']
createdOn = input_data['createdOn']
registrationDate = input_data['registrationDate']
fullName = input_data['fullName']

nameArray = fullName.split(" ")
firstName = nameArray[0]
lastName = nameArray[-1]

def format_date(d):
    if len(d) > 10:
        formatted = d[:10]
        return formatted
    else:
        return None

if gender == '1':
    gender = 'Not set'
elif gender == '2':
    gender = 'Male'
elif gender == '3':
    gender = 'Female'
elif gender == '4':
    gender = 'Other'
else:
    gender = 'Rather not say'

renewalDate = format_date(renewalDate)
dateOfBirth = format_date(dateOfBirth)
createdOn = format_date(dateOfBirth)
registrationDate = format_date(registrationDate)

output = [{
    'gender': gender,
    'renewalDate': renewalDate,
    'dateOfBirth': dateOfBirth,
    'createdOn': createdOn,
    'registrationDate': registrationDate,
    'firstName': firstName,
    'lastName': lastName
}]

Here is Zapier reporting the error in task history

Upvotes: 0

Views: 990

Answers (1)

Michael Case
Michael Case

Reputation: 518

When using the Python code module in Zapier the key-value pairs you supply for the input_data variable are converted into a Python dictionary object. The error you are receiving is a result of attempting to retrieve a key from the input_data dictionary that is not there. Noted in the documentation:

d[key]:
Return the item of d with key key. Raises a KeyError if key is not in the map.

I would instead recommend retrieving values from the input_data dictionary using the d.get(key) method.

get(key[, default]):
Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

This is handy because rather than returning an error if it does not find a matching key it simply returns None, or you can specify a default return value if the key is not found d.get(key, default). You can read more about it in the link provided above.

Hope this helps.

Upvotes: 3

Related Questions