例如我有一个
{
"key1":[1,2,3],
"key2":[1,2]
}
我想将其改为
[{"key1":1, "key2":1},{"key1":1, "key2":2},{"key1":2, "key2":1}...]
我通过使用eval实现这一点,我认为递归也有帮助。但有没有更好的解决方案?
答案 0 :(得分:3)
d = {
"key1":[1,2,3],
"key2":[1,2]
}
from itertools import product
[{'key1':i,'key2':j} for i,j in product(d['key1'],d['key2'])]
[{'key1': 1, 'key2': 1}, {'key1': 1, 'key2': 2}, {'key1': 2, 'key2': 1}, {'key1': 2, 'key2': 2}, {'key1': 3, 'key2': 1}, {'key1': 3, 'key2': 2}]