将带有列表值的 OrderedDict 扩展为字典列表
我有一个带有值列表的 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}]}]
I have an OrderedDict with a list of values:
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}]}]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我们可以使用
zip
一起遍历“key1”和“key2”下的值,并在迭代时附加到输出列表。此外,内部字典的值也必须一起遍历,因此我们解压lst[0]
的值并使用 zip 来构造内部字典:与嵌套理解相同的代码:
输出:
We could use
zip
to traverse values under both "key1" and "key2" together and append to an output list as we iterate. Moreover, the values of the inner dict have to be traversed together as well, so we unpack the values oflst[0]
and use zip yet to construct the inner dictionary:The same code as a nested comprehension:
Output: