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: 
Problem with the current code/algorithm
---------------------------------------

The problem with this particular code is that it ends up overwriting the content of `row_data`, and append two copies of essentially the same memory location in the list, hence the same value as the last item. What you would do, is to reset `row_data` at every `message`, like this:

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

response = []

for message in messages:
    row_data = {}    # create new empty dict

    for k, v in message.items():  # fill the dict with key->value
        row_data[k] = str(v)

    response.append(row_data)    # append the new item to the list

print(response)

```

Are there better ways?
----------------------

> 
> As you added information about it not being JSON serializable, this might not apply directly. Leaving this portion as it might help someone in the future.
> 
> 
> 

Of course, especially because what you are doing is dealing with JSON data, which is natively handled in Python with the `json` library. Depending on what exactly you want to achieve, you should be looking at methods in that library.
Your array already contains dictionaries, so you can simply use the `JSON` module.

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

```