Python – 具有最大唯一值的键
给定一个带有值列表的字典,提取其值具有最多唯一值的键。
Input : test_dict = {“Gfg” : [5, 7, 9, 4, 0], “is” : [6, 7, 4, 3, 3], “Best” : [9, 9, 6, 5, 5]}
Output : “Gfg”
Explanation : “Gfg” having max unique elements i.e 5.
Input : test_dict = {“Gfg” : [5, 7, 7, 7, 7], “is” : [6, 7, 7, 7], “Best” : [9, 9, 6, 5, 5]}
Output : “Best”
Explanation : 3 (max) unique elements, 9, 6, 5 of “Best”.
方法#1:使用循环
这是可以执行此任务的粗暴方式。在此,我们迭代所有列表值并检查每个键的值计数,提取具有最大唯一值的键。
Python3
# Python3 code to demonstrate working of
# Key with maximum unique values
# Using loop
# initializing dictionary
test_dict = {"Gfg" : [5, 7, 5, 4, 5],
"is" : [6, 7, 4, 3, 3],
"Best" : [9, 9, 6, 5, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
max_val = 0
max_key = None
for sub in test_dict:
# test for length using len()
# converted to set for duplicates removal
if len(set(test_dict[sub])) > max_val:
max_val = len(set(test_dict[sub]))
max_key = sub
# printing result
print("Key with maximum unique values : " + str(max_key))
Python3
# Python3 code to demonstrate working of
# Key with maximum unique values
# Using sorted() + lambda() + set() + values() + len()
# initializing dictionary
test_dict = {"Gfg" : [5, 7, 5, 4, 5],
"is" : [6, 7, 4, 3, 3],
"Best" : [9, 9, 6, 5, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# one-liner to solve a problem
# sorted used to reverse sort dictionary
max_key = sorted(test_dict, key = lambda ele: len(
set(test_dict[ele])), reverse = True)[0]
# printing result
print("Key with maximum unique values : " + str(max_key))
The original dictionary is : {‘Gfg’: [5, 7, 5, 4, 5], ‘is’: [6, 7, 4, 3, 3], ‘Best’: [9, 9, 6, 5, 5]}
Key with maximum unique values : is
方法 #2:使用 sorted() + lambda() + set() + values() + len()
上述功能的组合可以用来解决这个问题。在此,我们根据设置的长度对字典键进行反向排序并返回第一个结果。
Python3
# Python3 code to demonstrate working of
# Key with maximum unique values
# Using sorted() + lambda() + set() + values() + len()
# initializing dictionary
test_dict = {"Gfg" : [5, 7, 5, 4, 5],
"is" : [6, 7, 4, 3, 3],
"Best" : [9, 9, 6, 5, 5]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# one-liner to solve a problem
# sorted used to reverse sort dictionary
max_key = sorted(test_dict, key = lambda ele: len(
set(test_dict[ele])), reverse = True)[0]
# printing result
print("Key with maximum unique values : " + str(max_key))
The original dictionary is : {‘Gfg’: [5, 7, 5, 4, 5], ‘is’: [6, 7, 4, 3, 3], ‘Best’: [9, 9, 6, 5, 5]}
Key with maximum unique values : is