Python – 字典中长度最短的键
有时,在使用Python列表时,我们可能会遇到需要返回具有最小列表长度的键作为值的问题。这可以应用于我们处理数据的领域。让我们讨论可以执行此任务的某些方式。
方法 #1:使用len() + loop + items()
上述功能的组合可用于执行此任务。在此,我们迭代字典的键并使用 len() 返回长度等于最小列表长度的所有键。
# Python3 code to demonstrate working of
# Keys with shortest length lists in dictionary
# Using len() + loop + items()
# initializing dictionary
test_dict = {'gfg' : [4, 5],
'is' : [9, 7, 3, 10],
'best' : [11, 34],
'for' : [6, 8, 2],
'geeks' : [12, 24]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Keys with shortest length lists in dictionary
# Using len() + loop + items()
min_val = min([len(test_dict[ele]) for ele in test_dict])
res = []
for ele in test_dict:
if len(test_dict[ele]) == min_val:
res.append(ele)
# printing result
print("The required keys are : " + str(res))
输出 :
The original dictionary is : {‘is’: [9, 7, 3, 10], ‘gfg’: [4, 5], ‘best’: [11, 34], ‘for’: [6, 8, 2], ‘geeks’: [12, 24]}
The required keys are : [‘gfg’, ‘best’, ‘geeks’]
方法#2:使用列表推导
也可以使用列表理解的简写来执行此任务。在此,我们执行与上述任务类似的任务,但以速记方式。
# Python3 code to demonstrate working of
# Keys with shortest length lists in dictionary
# Using list comprehension
# initializing dictionary
test_dict = {'gfg' : [4, 5],
'is' : [9, 7, 3, 10],
'best' : [11, 34],
'for' : [6, 8, 2],
'geeks' : [12, 24]}
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
# Keys with shortest length lists in dictionary
# Using list comprehension
min_val = min([len(test_dict[ele]) for ele in test_dict])
res = [key for key, val in test_dict.items() if len(val) == min_val]
# printing result
print("The required keys are : " + str(res))
输出 :
The original dictionary is : {‘is’: [9, 7, 3, 10], ‘gfg’: [4, 5], ‘best’: [11, 34], ‘for’: [6, 8, 2], ‘geeks’: [12, 24]}
The required keys are : [‘gfg’, ‘best’, ‘geeks’]