好的,所以我有两个字典。
dictionary_1 = {'status': ['online', 'Away', 'Offline'],
'Absent':['yes', 'no', 'half day']}
dictionary_2 = {'healthy': ['yes', 'no'],
'insane': ['yes', 'no']
现在我需要将它们组合起来,以便获得一个新字典:
{'status': ['online', 'online', 'away', 'away', 'Offline', 'Offline'],
'Absent': ['yes', 'yes', 'no', 'no', 'half day', 'half day'],
'healthy': ['yes', 'no', 'yes', 'no', 'yes', 'no'],
'insane': ['yes', 'no', 'yes', 'no', 'yes', 'no']
}
这是一个很晚的更新,但如果有人感兴趣,我找到了一种无需 itertools 的方法。
def cartesian_product(dict1, dict2):
cartesian_dict = {}
dict1_length = len(list(dict1.values())[0])
dict2_length = len(list(dict2.values())[0])
h = []
for key in dict1:
for value in dict1[key]:
if not key in cartesian_dict:
cartesian_dict[key] = []
cartesian_dict[key].extend([value]*dict2_length)
else:
cartesian_dict[key].extend([value]*dict2_length)
for key in dict2:
cartesian_dict[key] = dict2[key]*dict1_length
return cartesian_dict