简体   繁体   English

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

[英]Expand OrderedDict with list values to a list of dictionaries

I have an OrderedDict with a list of values:我有一个带有值列表的 OrderedDict:

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

I'd like to transform this to a list of dictionaries where the lists in the values of the inner dictionaries expanded across separate dictionaries in a list:我想将其转换为字典列表,其中内部字典值中的列表扩展到列表中的不同字典:

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

We could use zip to traverse values under both "key1" and "key2" together and append to an output list as we iterate.我们可以使用zip一起遍历“key1”和“key2”下的值,并在迭代时使用 append 遍历 output 列表。 Moreover, the values of the inner dict have to be traversed together as well, so we unpack the values of lst[0] and use zip yet to construct the inner dictionary:此外,内部字典的值也必须一起遍历,因此我们解压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)

The same code as a nested comprehension:与嵌套理解相同的代码:

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'])]

Output: Output:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM