I have an array of strings (a1
): ["a", "b", "c"]
And another (a2
) that looks like this:
["1,20,300", "2,10,300", "3,40,300", "1, 20, 300, 4000"]
The wanted end result is:
{"a": [1,2,3,1], "b": [20, 10, 40, 20], "c": [300, 300, 300, 4000] }
It is safe to assume that a2[n].split(',')
will always give me the items in the correct order, i.e. the order of ["a", "b", "c"]
, just as in the example.
With this in mind, is it possible not having to loop twice and/or not having to assume the order of keys in a dictionary is consistent?
My solution would be:
a1 = ["a", "b", "c"]
a2 = ["1,20,300", "2,10,300", "3,40,300"]
result = {}
for i in a1:
result[i] = []
for e in a2:
splitted = e.split(",")
c = 0
for key,array in result.items():
result[key].append(splitted[c])
c = c+1
This requires many loops and assumes result.items() will always return the keys in the same order, which is not a safe assumption.
Is there any way to avoid this? Maybe using Pandas?