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

时间:2018-02-27 17:17:18

标签: python python-3.x list dictionary

我有一个清单

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

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

[{'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}]

我使用了以下代码

keys = ('test_case_id', 'test_suite_id')
list_of_case_suite_relation_rows = [dict(zip(keys, l)) for l in case_suite_relation_ids]

但我得到以下输出

[{'test_case_id': 1, 'test_suite_id': 2}, {'test_case_id': 1, 'test_suite_id': 1}]

任何解决方案如何解决?

2 个答案:

答案 0 :(得分: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}]

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

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

答案 1 :(得分:0)

如果您愿意使用第三方库,Pandas提供了一种解决方案:

import pandas as pd

d = pd.DataFrame(case_suite_relation_ids).T\
      .set_axis(['test_case_id', 'test_suite_id'], 1, inplace=False)\
      .to_dict('records')

结果:

[{'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}]