【问题标题】:Generating a list of dictionaries in python using lists that contain duplicate values使用包含重复值的列表在python中生成字典列表
【发布时间】:2018-02-27 17:17:18
【问题描述】:

我有一个清单

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}]

有什么办法解决吗?

【问题讨论】:

  • 你想得到[{'test_case_id': case, 'test_suite_id': suite} for case, suite in zip(*case_suite_relation_ids)]吗?

标签: python python-3.x list dictionary


【解决方案1】:

这是一种方法:

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
【解决方案2】:

如果您乐于使用第三方库,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}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-09-13
    • 2018-09-13
    • 2016-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-30
    • 2013-09-21
    相关资源
    最近更新 更多