我试图以可读的形式从字典(没有重复项)中获取键(str)和相应值(str)的所有唯一组合(不是排列,因为顺序并不重要)。
items_dict = {
'item1': {'value1', 'value2', 'value3'},
'item2': {'value1', 'value4'},
'item3': {'value5', 'value2', 'value6', 'value1'}
}
我将这些值放入集合中,以便可以将它们联合起来。也许使用字典和集合并不是解决这个问题的正确方法。
我尝试过:
comb = combinations((items_dict.items()), 2)
但随后得到了键和值的元组:
(('item2': {'value1', 'value4'}), ('item1': {'val ...
我需要如下所示的预期结果来识别键和相应值的组合:
'item1', 'item2': {'value1', 'value2', 'value3', 'value4'}
'item2', 'item 3': {'value5', 'value2', 'value6', 'value1', 'value4'}
'item3', 'item1': {'value1', 'value2', 'value3', 'value5', 'value6'}
最佳答案
所以你需要itertools.combinations
键的结果,然后组合这些键的值。
import itertools
from typing import Mapping, Tuple, Any
def get_combinations(d: Mapping[Any, set]) -> Mapping[Tuple[Any, Any], set]:
"""Combine keys into pairs and merge values together.
>>> d = {1: {1, 2}, 2: {3, 4}, 3: {1, 4}}
>>> get_combinations(d)
{(1, 2): {1, 2, 3, 4}, (1, 3): {1, 2, 4}, (2, 3): {1, 3, 4}}
"""
key_combos = itertools.combinations(d.keys(), 2)
result = {key_combo: set.union(*(d[key] for key in key_combo)) for key_combo in key_combos}
return result
关于python - 不重复的键和值的可能组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55933161/