[Numpy-discussion] Efficiently converting numpy record array to a list of dictionary

Robert Kern robert.kern@gmail....
Thu Feb 4 18:04:42 CST 2010


On Thu, Feb 4, 2010 at 16:26, Vishal Rana <ranavishal@gmail.com> wrote:
> How do I convert the numpy record array below:
> recs = [('Bill', 31, 260.0), ('Fred', 15, 145.0)]
> r = rec.fromrecords(recs, names='name, age, weight', formats='S30, i2, f4')
> to a list of dictionary like:
> [{'name': 'Bill', 'age': 31, 'weight': 260.0},
> 'name': 'Fred', 'age': 15, 'weight': 145.0}]

Assuming that your record array is only 1D:

In [6]: r.dtype.names
Out[6]: ('name', 'age', 'weight')

In [7]: names = r.dtype.names

In [8]: [dict(zip(names, record)) for record in r]
Out[8]:
[{'age': 31, 'name': 'Bill', 'weight': 260.0},
 {'age': 15, 'name': 'Fred', 'weight': 145.0}]

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco


More information about the NumPy-Discussion mailing list