Convert a Numpy 2 dimensional array to a mapped list of dictionaries

lokiysh :

I have a Numpy 2D array, and a list of headers. Each row of the Numpy array is a record to be mapped to the header list. In the end, I want to convert each record to a dictionary (and so have a list of dictionaries). For example:

A = [[1, 2, 3], [4, 5, 6]]
headers = ['a', 'b', 'c']

Output:

[{'a' : 1, 'b' : 2, 'c' : 3}, {'a' : 4, 'b' : 5, 'c' : 6}]

What is the fastest way to achieve this in Python? I have in the order of 10^4 rows and 10 headers, and running it is taking me roughly 0.3 seconds.

At this moment, I have the following code:

current_samples = A # The samples described above as input, a Numpy array
locations = []
for i, sample in enumerate(current_samples):
    current_location = dict()
    for index, dimension in enumerate(headers):
        current_location[dimension] = sample[index]
    locations.append(current_location)
Dani Mesejo :

Use zip + dict:

result = [dict(zip(headers, l)) for l in A]
print(result)

Output

[{'a': 1, 'b': 2, 'c': 3}, {'a': 4, 'b': 5, 'c': 6}]

With zip you create pair of items from the list and pass it to the dictionary constructor.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=394728&siteId=1