从包含重复列表值的字典中获取键,然后将它们对应的键存储在嵌套列表中

Get keys from a dictionary that contains duplicate list values, then store their corresponding keys in a nested list

我已经尽我所能用最好的方式来表达这一点,但如果我提供一个我正在努力实现的目标的例子,它可能会更清楚:

输入:

source_dictionary = {"person1": ["x1","x2","x3","x4"],
                     "person2": ["x1","x2","x3","x4"],
                     "person3": ["x1","x2"],
                     "person4": ["x1","x2"],
                     "person5": ["x1","x2"]
                    }

预期输出:

[["person1","person2"],["person3","person4","person5"]]

事实证明,处理字典中的列表是一项相当大的挑战。

抱歉,我忘了包括到目前为止我尝试过的内容。如上所述 - 我对列表有疑问:

rev_dict = {}
  
for key, value in source_dictionary.items():
    rev_dict.setdefault(value, set()).add(key)
      
result = [key for key, values in rev_dict.items()
                              if len(values) > 1]

假设你想通过相同的值连接键,使用 defaultdict:

source_dictionary = {"person1": ["x1","x2","x3","x4"],
                     "person2": ["x1","x2","x3","x4"],
                     "person3": ["x1","x2"],
                     "person4": ["x1","x2"],
                     "person5": ["x1","x2"]
                    }

from collections import defaultdict

d = defaultdict(list)
for key, value in source_dictionary.items():
    d[tuple(value)].append(key)
    
out = list(d.values())

替代 setdefault

d = {}
for key, value in source_dictionary.items():
    d.setdefault(tuple(value), []).append(key)
    
out = list(d.values())

输出:

[['person1', 'person2'], ['person3', 'person4', 'person5']]
source_dictionary = {"person1": ["x1","x2","x3","x4"],
                     "person2": ["x1","x2","x3","x4"],
                     "person3": ["x1","x2"],
                     "person4": ["x1","x2"],
                     "person5": ["x1","x2"]
                    }

L = []
for i in source_dictionary.values():
    K = []
    for j in source_dictionary.keys():
        if source_dictionary[j] == i :
            K.append(j)
    if K not in L:
        L.append(K)

print(L)