mallix mallix - 3 months ago 9
Python Question

Unable to append data to array

I am retrieving a record set from a database.

Then using a for statement I am trying to construct my data to match a 3rd party API.

But I get this error and can't figure it out:


"errorType": "TypeError", "errorMessage": "list indices must be
integers, not str"

"messages['english']['merge_vars']['vars'].append({"


Below is my code:

cursor = connect_to_database()

records = get_records(cursor)

template = dict()

messages = dict()

template['english'] = "SOME_TEMPLATE reminder-to-user-english"

messages['english'] = {
'subject': "Reminder (#*|code|*)",
'from_email': 'mail@mail.com',
'from_name': 'Notifier',
'to': [],
'merge_vars': [],
'track_opens': True,
'track_clicks': True,
'important': True
}

for record in records:

record = dict(record)

if record['lang'] == 'english':

messages['english']['to'].append({
'email': record['email'],
'type': 'to'
})

messages['english']['merge_vars'].append({
'rcpt': record['email']
})

for (key, value) in record.iteritems():

messages['english']['merge_vars']['vars'].append({
'name': key,
'content': value
})

else:

template['other'] = "SOME_TEMPLATE reminder-to-user-other"

close_database_connection()

return messages


The goal is to get something like this below:

messages = {
'subject': "...",
'from_email': "...",
'from_name': "...",
'to': [
{
'email': '...',
'type': 'to',
},
{
'email': '...',
'type': 'to',
}
],
'merge_vars': [
{
'rcpt': '...',
'vars': [
{
'content': '...',
'name': '...'
},
{
'content': '...',
'name': '...'
}
]
},
{
'rcpt': '...',
'vars': [
{
'content': '...',
'name': '...'
},
{
'content': '...',
'name': '...'
}
]
}
]
}

Answer

This code seems to indicate that messages['english']['merge_vars'] is a list, since you initialize it as such:

messages['english'] = {
    ...
    'merge_vars': [],
    ...
}

And call append on it:

messages['english']['merge_vars'].append({
    'rcpt': record['email']
})

However later, you treat it as a dictionary when you call:

messages['english']['merge_vars']['vars']

It seems what you want is something more like:

vars = [{'name': key, 'content': value} for key, value in record.iteritems()]
messages['english']['merge_vars'].append({
    'rcpt': record['email'],
    'vars': vars,
})

Then, the for loop is unnecessary.

Comments