Unable to append data to array
<p>I am retrieving a record set from a database.<br>
Then using a <strong>for</strong> statement I am trying to construct my data to match a 3rd party API.</p>

<p>But I get this error and can't figure it out:  </p>

<blockquote>
  <p>"errorType": "TypeError",   "errorMessage": "list indices must be
  integers, not str"<br>
  "messages['english']['merge_vars']['vars'].append({"</p>
</blockquote>

<p>Below is my code:</p>

<pre><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
</code></pre>

<p>The goal is to get something like this below:  </p>

<pre><code>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': '...'
      }
    ]
  }
 ]
}
</code></pre>

<p>What the error is saying is that you are trying to access an array element with the help of string not index (int).</p>

<p>I believe your mistake is in this line:</p>

<pre><code>messages['english']['merge_vars']['vars'].append({..})
</code></pre>

<p>You declared <code>merge_vars</code> as array like so:</p>

<pre><code>'merge_vars': []
</code></pre>

<p>So, you either make it <code>dict</code> like this:</p>

<pre><code>'merge_vars': {}
</code></pre>

<p>Or, use it as array:</p>

<pre><code>messages['english']['merge_vars'].append({..})
</code></pre>

<p>Hope it helps</p>

python python-2.7