List of dicts to/from dict of lists
Perhaps consider using numpy:
import numpy as np
arr = np.array([(0, 2), (1, 3)], dtype=[('a', int), ('b', int)])
print(arr)
# [(0, 2) (1, 3)]
Here we access columns indexed by names, e.g. 'a'
, or 'b'
(sort of like DL
):
print(arr['a'])
# [0 1]
Here we access rows by integer index (sort of like LD
):
print(arr[0])
# (0, 2)
Each value in the row can be accessed by column name (sort of like LD
):
print(arr[0]['b'])
# 2
For those of you that enjoy clever/hacky one-liners.
Here is DL
to LD
:
v = [dict(zip(DL,t)) for t in zip(*DL.values())]
print(v)
and LD
to DL
:
v = {k: [dic[k] for dic in LD] for k in LD[0]}
print(v)
LD
to DL
is a little hackier since you are assuming that the keys are the same in each dict
. Also, please note that I do not condone the use of such code in any kind of real system.