Reputation: 317
I have a list
case_suite_relation_ids= [[1, 2, 3, 1, 2, 3, 1], [1, 1, 1, 2, 2, 2, 3]]
and want to generate a list of dictionaries in the following manner
[{'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}]
I used the following code
keys = ('test_case_id', 'test_suite_id')
list_of_case_suite_relation_rows = [dict(zip(keys, l)) for l in case_suite_relation_ids]
but I get the following output
[{'test_case_id': 1, 'test_suite_id': 2}, {'test_case_id': 1, 'test_suite_id': 1}]
Any solutions how to solve it ?
Upvotes: 2
Views: 118
Reputation: 164623
If you are happy to use a 3rd party library, Pandas offers a solution:
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')
Result:
[{'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}]
Upvotes: 0
Reputation: 164623
Here is one way:
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}]
Some people (not me) prefer the functional version:
d = list(map(lambda i, j: {'test_case_id': i, 'test_suite_id': j},
case_suite_relation_ids[0], case_suite_relation_ids[1]))
Upvotes: 9