constructing a message format from the fetchall result in python

Issue

*New to Programming

Question: I need to use the below "Data" (two rows as arrays) queried from sql and use it to create the message structure below.

data from sql using fetchall()

Data = [[100,1,4,5],[101,1,4,6]]

##expected message structure

message = {
            "name":"Tom",
            "Job":"IT",
            "info": [
               {
                "id_1":"100",
                "id_2":"1",
                "id_3":"4",
                "id_4":"5"
                },
               {
                "id_1":"101",
                "id_2":"1",
                "id_3":"4",
                "id_4":"6"
                },  
             ]
}

I tried to create below method to iterate over the rows and then input the values, this is was just a starting, but this was also not working

def create_message(data)
    for row in data:
       {
        "id_1":str(data[0][0],
        "id_2":str(data[0][1],
        "id_3":str(data[0][2],
        "id_4":str(data[0][3],
       }

Latest Code

def create_info(data):
    info = []
    for row in data:
        temp_dict = {"id_1_tom":"","id_2_hell":"","id_3_trip":"","id_4_clap":""}
        for i in range(0,1):
            temp_dict["id_1_tom"] = str(row[i])
            temp_dict["id_2_hell"] = str(row[i+1])
            temp_dict["id_3_trip"] = str(row[i+2])
            temp_dict["id_4_clap"] = str(row[i+3])
        info.append(temp_dict)
    return info

Solution

Edit: Updated answer based on updates to the question and comment by original poster.

This function might work for the example you’ve given to get the desired output, based on the attempt you’ve provided:

def create_info(data):
    info = []
    for row in data:
        temp_dict = {}
        temp_dict['id_1_tom'] = str(row[0])
        temp_dict['id_2_hell'] = str(row[1])
        temp_dict['id_3_trip'] = str(row[2])
        temp_dict['id_4_clap'] = str(row[3])
        info.append(temp_dict)
    return info

For the input:

[[100, 1, 4, 5],[101,1,4,6]]

This function will return a list of dictionaries:

[{"id_1_tom":"100","id_2_hell":"1","id_3_trip":"4","id_4_clap":"5"}, 
{"id_1_tom":"101","id_2_hell":"1","id_3_trip":"4","id_4_clap":"6"}]

This can serve as the value for the key info in your dictionary message. Note that you would still have to construct the message dictionary.

Answered By – randommathguy

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published