I have a dict that like this
{'id':[0, 1, 2, 3, 4, 5],
'code':['A1', 'A2', 'A3', 'A4', 'A5', 'A6'],
'price':['35', '23', '54', '17', '68', '199']
}
How can I make it look like this:
data= [
[0, 'A1', '35'],
[1, 'A2', '23'],
[2, 'A3', '54'],
[3, 'A4', '17'],
[4, 'A5', '68'],
[5, 'A6', '199'],
]
I know that I can do it in python but just want someone to point me in the direction of how to do it, because I don't know where to start
CodePudding user response:
You can use a transpose operation -- note that zip()
returns an iterable of tuples, so we need to transform them to lists using map()
:
list(map(list, zip(*data.values())))
This outputs:
[[0, 'A1', '35'], [1, 'A2', '23'], [2, 'A3', '54'], [3, 'A4', '17'], [4, 'A5', '68'], [5, 'A6', '199']]
CodePudding user response:
You can use pandas as follows
import pandas as pd
my_dict = {'id':[0, 1, 2, 3, 4, 5],
'code':['A1', 'A2', 'A3', 'A4', 'A5', 'A6'],
'price':['35', '23', '54', '17', '68', '199']
}
data = pd.DataFrame.from_dict(my_dict).to_numpy()
print(data)
>>>
[[0 'A1' '35']
[1 'A2' '23']
[2 'A3' '54']
[3 'A4' '17']
[4 'A5' '68']
[5 'A6' '199']]