-4

Lets say, I have two arrays:

Array1

from = ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04']

And then array2:

to = ['2022-02-01', '2022-02-02', '2022-02-03', '2022-02-04']

Now by using the both, i need to create a combined structure array without changing the orders:

Lets say, the expected output is as follows:

output = [{'from': '2022-01-01', 'to': '2022-02-01'}, 
{'from': '2022-01-02', 'to': '2022-02-02'}, 
{'from': '2022-01-03', 'to': '2022-02-03'}, 
{'from': '2022-01-04', 'to': '2022-02-04'}]

The [0] of from should match [0] of to data. Likewise, how to convert the array ? Am yet to start and dont know where to start so i dont have any code to show. Please help

2 Answers2

1

You can use zip and list comprehension for that -

from_ = ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04']
output = [{'from': f, 'to': t} for f, t in zip(from_, to)]
Tom Ron
  • 5,906
  • 3
  • 22
  • 38
0

You can use the zip function to take on one value from each list at a time. For example:

from_arr = ['2022-01-01', '2022-01-02', '2022-01-03', '2022-01-04']
to_arr = ['2022-02-01', '2022-02-02', '2022-02-03', '2022-02-04']
result = []
for from_elem, to_elem in zip(from_arr, to_arr):
  result.append({"from":from_elem,"to":to_elem})

print(result)

Advay168
  • 607
  • 6
  • 10