将具有列表值的 OrderedDict 扩展到字典列表

Expand OrderedDict with list values to a list of dictionaries

我有一个带有值列表的 OrderedDict:

OrderedDict([('key1', ['value1', 'value2']),
             ('key2',
              [[{'name': ['A', 'B'], 'amount': ['1', '2']}],
               [{'name': ['C', 'D'], 'amount': ['3', '4']}]])])

我想将其转换为字典列表,其中内部字典值中的列表扩展到列表中的不同字典:

[{'key1': 'value1',
  'key2': [{'name': 'A', 'amount': 1}, {'name': 'B', 'amount': 2}]},
 {'key1': 'value2',
  'key2': [{'name': 'C', 'amount': 3}, {'name': 'D', 'amount': 4}]}]

我们可以使用 zip 一起遍历“key1”和“key2”下的值,并在迭代时附加到输出列表。此外,内部字典的值也必须一起遍历,所以我们解压 lst[0] 的值并使用 zip 尚未构建内部字典:

out = []
for v, lst in zip(data['key1'], data['key2']):
    d = {'key1': v, 'key2': []}
    for tpl in zip(*lst[0].values()):
        mid = {key: val for key, val in zip(lst[0], tpl)}
        d['key2'].append(mid)
    out.append(d)

与嵌套理解相同的代码:

out = [{'key1': v, 'key2': [{key: val for key, val in zip(lst[0], tpl)} for tpl in zip(*lst[0].values())]} for v, lst in zip(data['key1'], data['key2'])]

输出:

[{'key1': 'value1',
  'key2': [{'name': 'A', 'amount': '1'}, {'name': 'B', 'amount': '2'}]},
 {'key1': 'value2',
  'key2': [{'name': 'C', 'amount': '3'}, {'name': 'D', 'amount': '4'}]}]