Question: In python how do you iterate and append a dict of each object from an array into a new array (for serializing the data to return json in a GET request)? The existing iteration is returning duplicates of the last object in the array as shown in current results below and not printing the intended results below.

**Note:**

*I am using SQLAlchemy's .get.all() to get the initial messages and they serve as not JSON serializable, I am trying to stay away from libraries such as Marshmallow. Flask `.jsonify(response)` and `json.dumps(response)` throw errors.*

```
message = [
        {
            'id': 1,
            'message': the first message,
        },
        {
            'id': 2,
            'message': the second message
        }
    ]

response = []
row_data = {}

for message in messages:
    for k, v in message.items():
        row_data[k] = str(v)
    response.append(row_data)
print(response)

```

current response:

```
[
    {
        'id': '2',
        'message': 'the second message',
    },
    {
        'id': '2',
        'message': 'the second message'
    }
]

```

intended response:

```
[
    {
        'id': '1',
        'message': 'the first message',
    },
    {
        'id': '2',
        'message': 'the second message'
    }
]

```

Answer: 
Your problem here is that you are not breaking the connection from `row_data` to the dictionary you append to `response`.

Because of this, after the first iteration, `row_data` still points to the same dictionary that is the first element in the `response` list. You then modify the values stored in the dictionary, and append it a second time. This modification changes the dictionary, but because you have two references to the same dict, you think that you're getting two copies of the data -- you're not.

This problem is similar to the [**Mutable Default Argument**](https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments) problem, in that a single collection item is being re-used when it shouldn't be.

As a solution, I would suggest moving the initializer inside your loop. This will create a new dictionary each time:

```
for message in messages:
    row_data = {}
    for k, v in message.items():
        row_data[k] = str(v)
    response.append(row_data)

```

A better solution would be to use a different mechanism to create the dictionary. All you are doing is copying the items, so consider using the `dict.copy()` method, or the `dict()` builder.
Your array already contains dictionaries, so you can simply use the `JSON` module.

```
import json
output_string = json.dumps(messages)

```