如何"扩展"一个带有iterables的dict到Python的dict列表中

时间:2015-07-27 10:34:32

标签: python functional-programming

例如我有一个

{
    "key1":[1,2,3],
    "key2":[1,2]
}

我想将其改为

[{"key1":1, "key2":1},{"key1":1, "key2":2},{"key1":2, "key2":1}...]

我通过使用eval实现这一点,我认为递归也有帮助。但有没有更好的解决方案?

1 个答案:

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