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

Keith Goodman kwgoodman@gmail....
Thu Feb 4 17:59:30 CST 2010


On Thu, Feb 4, 2010 at 3:46 PM, Keith Goodman <kwgoodman@gmail.com> wrote:
> On Thu, Feb 4, 2010 at 2:26 PM, 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}]
>
> It looks like a two-body problem, so it should be solvable.

Do you already have recs as a list? Then:

>> recs = [('Bill', 31, 260.0), ('Fred', 15, 145.0)]
>> [{'name': rec[0], 'age': rec[1], 'weight': rec[2]} for rec in recs]

[{'age': 31, 'name': 'Bill', 'weight': 260.0},
 {'age': 15, 'name': 'Fred', 'weight': 145.0}]


More information about the NumPy-Discussion mailing list