1 回答

TA贡献1829条经验 获得超7个赞
您可以遍历所有键并在处理的第一个键上创建新的 Ordered dicts,后面的键添加到较早创建的 dicts。
对于每个键,您遍历所有值并将它们放入单个 Ordered dicts 中,然后添加到列表中(只要您的输入值列表都具有相同数量的数据,这将起作用):
from collections import OrderedDict
ab = OrderedDict([
('part', ['8888822701B', '8889012006B', '8889012013B', '8889012014B', '8889012016C',
'8889012019B', '8889012020C', '8889012021D', '8889012022B']),
('file', ['0', '1', '2', '3', '4', '5', '6', '7', '8']),
('estimatedtime', ['100', ' 100', ' 100', ' 100', ' 100', ' 100', ' 100', ' 100', ' 100']),
('signature', ['{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}']),
('otherpartsignature', ['{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}'])])
listOfDicts = []
for key,values in ab.items():
if not dicts: # create all new OrderedDicts when processing the values of first key
for v in values:
listOfDicts.append(OrderedDict({key:v}))
else:
for idx,v in enumerate(values): # use the earlier created Ordered dicts and add to them
d = listOfDicts[idx]
d[key]=v
print(listOfDicts)
输出:
[OrderedDict([('part', '8888822701B'), ('file', '0'), ('estimatedtime', '100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
OrderedDict([('part', '8889012006B'), ('file', '1'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
OrderedDict([('part', '8889012013B'), ('file', '2'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
OrderedDict([('part', '8889012014B'), ('file', '3'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
OrderedDict([('part', '8889012016C'), ('file', '4'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
OrderedDict([('part', '8889012019B'), ('file', '5'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
OrderedDict([('part', '8889012020C'), ('file', '6'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
OrderedDict([('part', '8889012021D'), ('file', '7'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')]),
OrderedDict([('part', '8889012022B'), ('file', '8'), ('estimatedtime', ' 100'), ('signature', '{}'), ('otherpartsignature', '{}')])]
添加回答
举报