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



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

输入:

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)

相关内容

  • 没有找到相关文章

最新更新