How to use dictionary comprehension. In Python

Step-by-step approach:

  • Initialize a variable min_length with the length of the shortest list value in the dictionary.
  • Use dictionary comprehension to create a new dictionary with only the key-value pairs where the value list has length equal to min_length.
  • Extract the keys from the new dictionary as a list.

Below is the implementation of the above approach:

Python3




# Python3 code to demonstrate working of
# Keys with shortest length lists in dictionary
# Using dictionary 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 dictionary comprehension
min_length = min(len(lst) for lst in test_dict.values())
res = {k: v for k, v in test_dict.items() if len(v) == min_length}
keys = list(res.keys())
 
# printing result
print("The required keys are : " + str(keys))


Output

The original dictionary is : {'gfg': [4, 5], 'is': [9, 7, 3, 10], 'best': [11, 34], 'for': [6, 8, 2], 'geeks': [12, 24]}
The required keys are : ['gfg', 'best', 'geeks']

Time complexity: O(n), where n is the number of key-value pairs in the dictionary.
Auxiliary space: O(k), where k is the number of keys in the new dictionary created by dictionary comprehension.



Python – Keys with shortest length lists in dictionary

Sometimes, while working with Python lists, we can have problem in which we need to return the keys which have minimum lengths of lists as values. This can have application in domains in which we work with data. Lets discuss certain ways in which this task can be performed. 

Similar Reads

Method #1: Using len() + loop + items()

The combination of above functions can be used to perform this task. In this, we iterate the keys of dictionary and return all the keys whose lengths equates the length of smallest list using len()....

Method #2: Using list comprehension

...

Method 3: Using dictionary comprehension.

This task can also be performed using a shorthand of list comprehension. In this, we perform the task similar to above task but in shorthand manner....