Home > Net >  How to I assign a column label/name to each element of a nested array within an array?
How to I assign a column label/name to each element of a nested array within an array?

Time:12-02

I have the following data:

header = ['EXPERIMENT_ID', 'SESSION_ID', 'TRIAL_END', 'TRIAL_START']

data = ([(1, 1,  85.3543804,  74.7716105),
       (1, 1,  95.3867684,  85.3710747),
       (1, 1, 105.4189535,  95.4033732)])

How do I make it such that all data[n][0] gets labelled as 'EXPERIMENT_ID', data[n][1] as 'SESSION_ID', data[n][2] as 'TRIAL_END' and data[n][3] as 'TRIAL_START'?

I am aware that dict() is the way to go for this combining process so I visualise it to be like:

datadict = (dict(EXPERIMENT_ID = 1, SESSION_ID= 1, TRIAL_END = 85.3543804, TRIAL_START = 74.7716105), (dict(EXPERIMENT_ID = 1, SESSION_ID= 1, TRIAL_END = 95.3867684, TRIAL_START = 85.3710747)...)

I currently have a for loop within a for loop that does this by accessing each variable one by one, but it is taking up a sizeable chunk of space within the script itself. I was wondering if there is a much more efficient way to do this assignment?

CodePudding user response:

We can use dict() and zip() together as mentioned in this link . The below code still uses a loop to iterate over the list.

header = ['EXPERIMENT_ID', 'SESSION_ID', 'TRIAL_END', 'TRIAL_START']
data = ([(1, 1,  85.3543804,  74.7716105),
        (1, 1,  95.3867684,  85.3710747),
        (1, 1, 105.4189535,  95.4033732)])
out = []
for d in data:
     out.append(dict(zip(header,d)))

print(out)
    [{'EXPERIMENT_ID': 1, 'SESSION_ID': 1, 'TRIAL_END': 85.3543804, 'TRIAL_START': 74.7716105}, {'EXPERIMENT_ID': 1, 'SESSION_ID': 1, 'TRIAL_END': 95.3867684, 'TRIAL_START': 85.3710747}, {'EXPERIMENT_ID': 1, 'SESSION_ID': 1, 'TRIAL_END': 105.4189535, 'TRIAL_START': 95.4033732}]
  • Related