Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine multiple numpy arrays into a dictionary list

I have the following array:

column_names = ['id', 'temperature', 'price']

And three numpy array as follows:

idArry = ([1,2,3,4,....])

tempArry = ([20.3,30.4,50.4,.....])

priceArry = ([1.2,3.5,2.3,.....])

I wanted to combine the above into a dictionary as follows:

table_dict = ( {'id':1, 'temperature':20.3, 'price':1.2 },
               {'id':2, 'temperature':30.4, 'price':3.5},...)

I can use a for loop together with append to create the dictionary but the list is huge at about 15000 rows. Can someone show me how to use python zip functionality or other more efficient and fast way to achieve the above requirement?

like image 806
Andrew Ng Avatar asked Mar 05 '23 13:03

Andrew Ng


1 Answers

You can use a listcomp and the function zip():

[{'id': i, 'temperature': j, 'price': k} for i, j, k in zip(idArry, tempArry, priceArry)]
# [{'id': 1, 'temperature': 20.3, 'price': 1.2}, {'id': 2, 'temperature': 30.4, 'price': 3.5}]

If your ids are 1, 2, 3... and you use a list you don’t need ids in your dicts. This is a redundant information in the list.

[{'temperature': i, 'price': j} for i, j in zip(tempArry, priceArry)]

You can use also a dict of dicts. The lookup in the dict must be faster than in the list.

{i: {'temperature': j, 'price': k} for i, j, k in zip(idArry, tempArry, priceArry)}
# {1: {'temperature': 20.3, 'price': 1.2}, 2: {'temperature': 30.4, 'price': 3.5}}
like image 150
Mykola Zotko Avatar answered May 13 '23 00:05

Mykola Zotko