使用包含重复值的列表在python中生成字典列表

Dee*_*ran 2 python dictionary list python-3.x

我有一份清单

case_suite_relation_ids= [[1, 2, 3, 1, 2, 3, 1], [1, 1, 1, 2, 2, 2, 3]]
Run Code Online (Sandbox Code Playgroud)

并希望以下列方式生成字典列表

[{'test_case_id': 1, 'test_suite_id': 1}, {'test_case_id': 2, 'test_suite_id': 1},{'test_case_id': 3, 'test_suite_id': 1}, {'test_case_id': 1, 'test_suite_id': 2}, {'test_case_id': 2, 'test_suite_id': 2}, {'test_case_id': 3, 'test_suite_id': 2}, {'test_case_id': 1, 'test_suite_id': 3}]
Run Code Online (Sandbox Code Playgroud)

我使用了以下代码

keys = ('test_case_id', 'test_suite_id')
list_of_case_suite_relation_rows = [dict(zip(keys, l)) for l in case_suite_relation_ids]
Run Code Online (Sandbox Code Playgroud)

但我得到以下输出

[{'test_case_id': 1, 'test_suite_id': 2}, {'test_case_id': 1, 'test_suite_id': 1}]
Run Code Online (Sandbox Code Playgroud)

任何解决方案如何解决?

jpp*_*jpp 9

这是一种方式:

case_suite_relation_ids= [[1, 2, 3, 1, 2, 3, 1], [1, 1, 1, 2, 2, 2, 3]]

d = [{'test_case_id': i, 'test_suite_id': j} for i, j in zip(*case_suite_relation_ids)]

# [{'test_case_id': 1, 'test_suite_id': 1},
#  {'test_case_id': 2, 'test_suite_id': 1},
#  {'test_case_id': 3, 'test_suite_id': 1},
#  {'test_case_id': 1, 'test_suite_id': 2},
#  {'test_case_id': 2, 'test_suite_id': 2},
#  {'test_case_id': 3, 'test_suite_id': 2},
#  {'test_case_id': 1, 'test_suite_id': 3}]
Run Code Online (Sandbox Code Playgroud)

有些人(不是我)更喜欢功能版:

d = list(map(lambda i, j: {'test_case_id': i, 'test_suite_id': j},
             case_suite_relation_ids[0], case_suite_relation_ids[1]))
Run Code Online (Sandbox Code Playgroud)

  • 你可以简单地写"这是最好的方式:"*+1 (3认同)