default = [{"One": 1, "Two": 2, "Three": 3}, {"One": 5, "Two": 6, "Three": 7},
{"One": 9, "Two": 10, "Three" : 11}]
varying = {"One": [12,13,14,15], "Two": [20,21,23], "Three": [12,44]}
result = [dict(d.items() + [(k, x)])
for d in default for k, v in varying.items() for x in v]
>>> result
[{'One': 1, 'Three': 12, 'Two': 2},
{'One': 1, 'Three': 44, 'Two': 2},
{'One': 1, 'Three': 3, 'Two': 20},
{'One': 1, 'Three': 3, 'Two': 21},
{'One': 1, 'Three': 3, 'Two': 23},
{'One': 12, 'Three': 3, 'Two': 2},
{'One': 13, 'Three': 3, 'Two': 2},
{'One': 14, 'Three': 3, 'Two': 2},
{'One': 15, 'Three': 3, 'Two': 2},
{'One': 5, 'Three': 12, 'Two': 6},
{'One': 5, 'Three': 44, 'Two': 6},
{'One': 5, 'Three': 7, 'Two': 20},
{'One': 5, 'Three': 7, 'Two': 21},
{'One': 5, 'Three': 7, 'Two': 23},
{'One': 12, 'Three': 7, 'Two': 6},
{'One': 13, 'Three': 7, 'Two': 6},
{'One': 14, 'Three': 7, 'Two': 6},
{'One': 15, 'Three': 7, 'Two': 6},
{'One': 9, 'Three': 12, 'Two': 10},
{'One': 9, 'Three': 44, 'Two': 10},
{'One': 9, 'Three': 11, 'Two': 20},
{'One': 9, 'Three': 11, 'Two': 21},
{'One': 9, 'Three': 11, 'Two': 23},
{'One': 12, 'Three': 11, 'Two': 10},
{'One': 13, 'Three': 11, 'Two': 10},
{'One': 14, 'Three': 11, 'Two': 10},
{'One': 15, 'Three': 11, 'Two': 10}]
这是使用普通 for 循环而不是列表推导的等价物:
result = []
for d in default:
for k, v in varying.items():
for x in v:
result.append(dict(d.items() + [(k, x)]))
请注意,在 Python 3.x 上,您需要list(d.items())
使用d.items()
.