I have a list of such dictionaries:
data = [{'x': 1, 'y': 10}, {'x': 3, 'y': 15}, {'x': 2, 'y': 1}, ... ]
I have a function (e.g. matplotlib.axis.plot ) that needs lists of x and y values. Therefore, I have to "transpose" the dictionary ".
First question: what do you call this operation? Is the "transpose" the correct term?
I tried this, but I'm looking for an efficient way (maybe there is a 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? I doubt that in these cases the hash of the string 'x' recounted every time?
Rugero turra
source share