>>> # a sequence of dictionaries in an interable called 'data'
>>> # assuming that not all dicts have the same keys
>>> pprint(data)
[{'x': 7.0, 'y1': 2.773, 'y2': 4.5, 'y3': 2.0},
{'x': 0.081, 'y1': 1.171, 'y2': 4.44, 'y3': 2.576},
{'y1': 0.671, 'y3': 3.173},
{'x': 0.242, 'y2': 3.978, 'y3': 3.791},
{'x': 0.323, 'y1': 2.088, 'y2': 3.602, 'y3': 4.43}]
>>> # get the unique keys across entire dataset
>>> keys = [list(dx.keys()) for dx in data]
>>> # flatten and coerce to 'set'
>>> keys = {itm for inner_list in keys for itm in inner_list}
>>> # create a map (look-up table) from each key
>>> # to a column in a NumPy array
>>> LuT = dict(enumerate(keys))
>>> LuT
{'y2': 0, 'y3': 1, 'y1': 2, 'x': 3}
>>> idx = list(LuT.values())
>>> # pre-allocate NUmPy array (100 rows is arbitrary)
>>> # number of columns is len(LuT.keys())
>>> D = NP.empty((100, len(LuT.keys())))
>>> keys = list(LuT.keys())
>>> keys
[0, 1, 2, 3]
>>> # now populate the array from the original data using LuT
>>> for i, row in enumerate(data):
D[i,:] = [ row.get(LuT[k], 0) for k in keys ]
>> D[:5,:]
array([[ 4.5 , 2. , 2.773, 7. ],
[ 4.44 , 2.576, 1.171, 0.081],
[ 0. , 3.173, 0.671, 0. ],
[ 3.978, 3.791, 0. , 0.242],
[ 3.602, 4.43 , 2.088, 0.323]])
将最后的结果(D 的前 5 行)与上面的 数据进行比较
请注意,每行(单个字典)的排序保留了一组不完整的键 - 换句话说,第 2 列 D 始终 对应于键入到 y2、 等的值,即使数据中的给定行没有为该键存储的值; eg,看data的第三行,只有两个key/value对,在D的第三行,第一列和最后一列都是0,这些列对应keys x 和 y2,实际上是缺少的两个键