I have a list of dictionaries like this:
data = [{'x': 1, 'y': 10},
{'x': 3, 'y': 15},
{'x': 2, 'y': 1},
... ]
I have a function (for example matplotlib.axis.plot
) which needs lists of x
and y
values. So I have to "transpose" the dictionary".
First question: what do you call this operation? Is "transpose" the correct term?
I've tried this, but I'm searching for an efficient way (maybe there are some special numpy
function):
x = range(100)
y = reversed(range(100))
d = [dict((('x',xx), ('y', yy))) for (xx, yy) in zip(x,y)]
# d is [{'y': 99, 'x': 0}, {'y': 98, 'x': 1}, ... ]
timeit.Timer("[dd['x'] for dd in d]", "from __main__ import d").timeit()
# 6.803985118865967
from operator import itemgetter
timeit.Timer("map(itemgetter('x'), d)", "from __main__ import d, itemgetter").timeit()
# 7.322326898574829
timeit.Timer("map(f, d)", "from __main__ import d, itemgetter; f=itemgetter('x')").timeit()
# 7.098556041717529
# quite dangerous
timeit.Timer("[dd.values()[1] for dd in d]", "from __main__ import d").timeit()
# 19.358459949493408
Is there a better solution? My doubt is: in these cases the hash of the string 'x'
is recomputed every time?