Python程序将字典中具有相似值的键分组
给定一个值作为列表的字典。将所有具有相似值的键组合在一起。
Input : test_dict = {“Gfg”: [5, 6], “is”: [8, 6, 9], “best”: [10, 9], “for”: [5, 2], “geeks”: [19]}
Output : [[‘Gfg’, ‘is’, ‘for’], [‘is’, ‘Gfg’, ‘best’], [‘best’, ‘is’], [‘for’, ‘Gfg’]]
Explanation : Gfg has 6, is has 6, and for has 5 which is also in Gfg hence, grouped.
Input : test_dict = {“Gfg”: [6], “is”: [8, 6, 9], “best”: [10, 9], “for”: [5, 2]}
Output : [[‘Gfg’, ‘is’], [‘is’, ‘Gfg’, ‘best’], [‘best’, ‘is’]]
Explanation : Gfg has 6, is has 6, hence grouped.
方法:使用循环 + any() + len()
以上功能的组合可以解决这个问题。在这里,我们使用 any() 检查每个键是否与任何值匹配,len() 用于检查匹配键是否超过 1。迭代部分使用循环进行。
Python3
# Python3 code to demonstrate working of
# Group keys with similar values in Dictionary
# Using loop + any() + len()
# initializing dictionary
test_dict = {"Gfg": [5, 6], "is": [8, 6, 9],
"best": [10, 9], "for": [5, 2],
"geeks": [19]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
res = []
for key in test_dict:
chr = [key]
for ele in test_dict:
# check with other keys
if key != ele:
# checking for any match in values
if any(i == j for i in test_dict[key] for j in test_dict[ele]):
chr.append(ele)
if len(chr) > 1:
res.append(chr)
# printing result
print("The dictionary after values replacement : " + str(res))
输出:
The original dictionary is : {‘Gfg’: [5, 6], ‘is’: [8, 6, 9], ‘best’: [10, 9], ‘for’: [5, 2], ‘geeks’: [19]}
The dictionary after values replacement : [[‘Gfg’, ‘is’, ‘for’], [‘is’, ‘Gfg’, ‘best’], [‘best’, ‘is’], [‘for’, ‘Gfg’]]