我如何从两个列表中获取字典的所有可能排列?

How do I get every permutation of a dictionary possibilies from two lists?

我有多组两个列表,我需要通过查看数据框中各行的每个排列将它们转换成一个字典。

例如,如果有一个列表['cat1','cat2']和一个列表['top1','top2'],我想要一个{'cat1':'top1','cat1':'top2','cat2':'top1','cat2':[=20= 的结果字典]}

这是我当前的代码,接近但最终使用了每个字母而不是字符串...

import pandas as pd

test_df = pd.DataFrame()
test_df['category'] = [['cat1'],['cat2'],['cat3','cat3.5'],['cat5']]
test_df['topic'] = [['top1'],[''],['top2','top3'],['top4']]


final_dict = {}
res = {}

for index, row in test_df.iterrows():
    print(row["category"], row["topic"])
    temp_keys = row["category"]
    temp_values = row["topic"]
    res = {}
    for test_key in temp_keys:
        #print(test_key)
        for test_value in temp_values:
            #print(test_value)
            #print(res)
            test_key = str(test_key)
            print(test_key)
            test_value = str(test_value)
            print(test_value)
            #res[key] = key
            #res = dict(zip(str(key),str(test_value)))
            res = dict(zip(str(test_key),str(test_value)))
            print(res)
            print('\n')

如果你想要一个元组列表而不是字典,你可以使用pd.MultiIndex.from_product:

out = test_df.apply(pd.MultiIndex.from_product, axis=1).apply(list)
>>> out
0                                       [(cat1, top1)]
1                                           [(cat2, )]
2    [(cat3, top2), (cat3, top3), (cat3.5, top2), (...
3                                       [(cat5, top4)]
dtype: object

>>> out.tolist()
[[('cat1', 'top1')],
 [('cat2', '')],
 [('cat3', 'top2'), ('cat3', 'top3'), ('cat3.5', 'top2'), ('cat3.5', 'top3')],
 [('cat5', 'top4')]]