Tamim Ad Dari Tamim Ad Dari - 8 months ago 25
Python Question

Convert a list of dictionaries to numpy matrix?

Let the given dictionaries are

d = [{'a':1,'b':4},{'b':2}]

So basically I want a matrix like this

| 'a' | 'b' |
| 1 | 4 |
| na | 2 |

How can I efficiently achieve this ?


The Pandas DataFrame constructor will immediately give you the result you are looking for:

import pandas as pd

The .values part on the end converts the result to a NumPy array, which is what you asked for. Some people would just work directly with the DataFrame instead.