Python - 所有可能的项目组合字典
有时,在处理数据时,我们可能会遇到一个问题,即我们提供了键和值列表的样本数据,我们需要将实际数据构造为所有可能的键和值列表的相似大小的组合。让我们讨论可以执行此任务的某些方式。
方法 #1:使用循环 + set()
可以采用上述功能的组合来解决这个问题。在此,我们最初提取集合列表中展平的所有项目。然后我们使用集合减法构造每个字典。
# Python3 code to demonstrate working of
# All possible items combination dictionary
# Using loop + set()
# initializing Dictionary
test_dict = {'gfg' : [1, 3], 'is' : [5, 6], 'best' : [4, 7]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# All possible items combination dictionary
# Using loop + set()
temp = [set([key]) | set(value) for key, value in test_dict.items() ]
res = {}
for sub in temp:
for key in sub:
res[key] = list(sub - set([key]))
# printing result
print("The all possible items dictionary : " + str(res))
The original dictionary is : {‘is’: [5, 6], ‘gfg’: [1, 3], ‘best’: [4, 7]}
The all possible items dictionary : {1: [3, ‘gfg’], 3: [1, ‘gfg’], 4: [‘best’, 7], 5: [‘is’, 6], 6: [‘is’, 5], 7: [4, ‘best’], ‘best’: [4, 7], ‘is’: [5, 6], ‘gfg’: [1, 3]}
方法 #2:使用remove() + loop + update()
这是可以执行此任务的另一种方式。在此,我们使用 remove() 执行删除已经存在的值的任务并构造新的字典项。
# Python3 code to demonstrate working of
# All possible items combination dictionary
# Using remove() + loop + update()
# initializing Dictionary
test_dict = {'gfg' : [1, 3], 'is' : [5, 6], 'best' : [4, 7]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# All possible items combination dictionary
# Using remove() + loop + update()
res = {}
for key, val in test_dict.items():
for ele in val:
temp = val[:]
temp.remove(ele)
res.update({ele: [key] + temp})
test_dict.update(res)
# printing result
print("The all possible items dictionary : " + str(test_dict))
The original dictionary is : {‘is’: [5, 6], ‘gfg’: [1, 3], ‘best’: [4, 7]}
The all possible items dictionary : {1: [3, ‘gfg’], 3: [1, ‘gfg’], 4: [‘best’, 7], 5: [‘is’, 6], 6: [‘is’, 5], 7: [4, ‘best’], ‘best’: [4, 7], ‘is’: [5, 6], ‘gfg’: [1, 3]}