# Python – Smallest K values in Dictionary

Many times while working with Python dictionary, we can have a particular problem to find the K minima of values in numerous keys. This problem is quite common while working with web development domain. Let’s discuss several ways in which this task can be performed.

### Smallest K values in Dictionary using itemgetter() + items() + sorted()

The combination of above method is used to perform this particular task. In this, we just sort the dictionary values expressed using itemgetter() and accessed using items().

## Python3

 `# Python3 code to demonstrate working of ` `# Smallest K values in Dictionary ` `# Using sorted() + itemgetter() + items() ` `from` `operator ``import` `itemgetter `   `# Initialize dictionary ` `test_dict ``=` `{``'gfg'` `: ``1``, ``'is'` `: ``4``, ``'best'` `: ``6``, ``'for'` `: ``7``, ``'geeks'` `: ``3` `} `   `# Initialize K ` `K ``=` `2`   `# printing original dictionary ` `print``(``"The original dictionary is : "` `+` `str``(test_dict)) `   `# Smallest K values in Dictionary ` `# Using sorted() + itemgetter() + items() ` `res ``=` `dict``(``sorted``(test_dict.items(), key ``=` `itemgetter(``1``))[:K]) `   `# printing result ` `print``(``"The minimum K value pairs are "` `+` `str``(res)) `

Output

```The original dictionary is : {'gfg': 1, 'is': 4, 'best': 6, 'for': 7, 'geeks': 3}
The minimum K value pairs are {'gfg': 1, 'geeks': 3}
```

### Smallest K values in Dictionary Using nsmallest()

This task can be performed using the nsmallest function. This is inbuilt function in heapq library which internally performs this task and can be used to do it externally. Has the drawback of printing just keys not values.

## Python3

 `# Python3 code to demonstrate working of ` `# Smallest K values in Dictionary ` `# Using nsmallest ` `from` `heapq ``import` `nsmallest `   `# Initialize dictionary ` `test_dict ``=` `{``'gfg'` `: ``1``, ``'is'` `: ``4``, ``'best'` `: ``6``, ``'for'` `: ``7``, ``'geeks'` `: ``3` `} `   `# Initialize K ` `K ``=` `2`   `# printing original dictionary ` `print``(``"The original dictionary is : "` `+` `str``(test_dict)) `   `# Smallest K values in Dictionary ` `# Using nsmallest ` `res ``=` `nsmallest(K, test_dict, key ``=` `test_dict.get) `   `# printing result ` `print``(``"The minimum K value pairs are "` `+` `str``(res)) `

Output

```The original dictionary is : {'gfg': 1, 'is': 4, 'best': 6, 'for': 7, 'geeks': 3}
The minimum K value pairs are ['gfg', 'geeks']
```

### Smallest K values in Dictionary Using sorted() + items() + lambda function

In this method, we can use the sorted() function along with the items() function and a lambda function to sort the key-value pairs based on the values and return the smallest K pairs.

## Python3

 `# Python3 code to demonstrate working of` `# Smallest K values in Dictionary` `# Using sorted() + items() + lambda function`   `# Initialize dictionary` `test_dict ``=` `{``'gfg'` `: ``1``, ``'is'` `: ``4``, ``'best'` `: ``6``, ``'for'` `: ``7``, ``'geeks'` `: ``3` `}`   `# Initialize K` `K ``=` `2`   `# printing original dictionary` `print``(``"The original dictionary is : "` `+` `str``(test_dict))`   `# Smallest K values in Dictionary` `# Using sorted() + items() + lambda function` `res ``=` `dict``(``sorted``(test_dict.items(), key ``=` `lambda` `x: x[``1``])[:K])`   `# printing result` `print``(``"The minimum K value pairs are "` `+` `str``(res))` `#This code is contributed by Edula Vinay Kumar Reddy`

Output

```The original dictionary is : {'gfg': 1, 'is': 4, 'best': 6, 'for': 7, 'geeks': 3}
The minimum K value pairs are {'gfg': 1, 'geeks': 3}
```

The time complexity of this method is O(nlogn) and Auxiliary space is O(n)
This method is similar to Method #1, but it uses a lambda function to sort the dictionary instead of the itemgetter function. The lambda function takes a tuple (key, value) and returns the value, which is used to sort the dictionary. The rest of the logic is the same as Method #1. The resulting output is the same as Method #1.

## Python3

 `# Define custom function` `def` `get_k_smallest_values(test_dict, K):` `    ``sorted_items ``=` `sorted``(test_dict.items(), key``=``lambda` `x: x[``1``])` `    ``k_smallest ``=` `{}` `    ``for` `i ``in` `range``(K):` `        ``k_smallest[sorted_items[i][``0``]] ``=` `sorted_items[i][``1``]` `    ``return` `k_smallest`   `# Initialize dictionary` `test_dict ``=` `{``'gfg'` `: ``1``, ``'is'` `: ``4``, ``'best'` `: ``6``, ``'for'` `: ``7``, ``'geeks'` `: ``3` `}`   `# Initialize K` `K ``=` `2`   `# printing original dictionary` `print``(``"The original dictionary is : "` `+` `str``(test_dict))`   `# Get K smallest values using custom function` `res ``=` `get_k_smallest_values(test_dict, K)`   `# printing result` `print``(``"The minimum K value pairs are "` `+` `str``(res))`

Output

```The original dictionary is : {'gfg': 1, 'is': 4, 'best': 6, 'for': 7, 'geeks': 3}
The minimum K value pairs are {'gfg': 1, 'geeks': 3}

```

Time complexity: O(nlogn) for sorting the dictionary items + O(K) for iterating over the K smallest value pairs. Overall time complexity is O(nlogn).
Auxiliary space: O(K) for storing the K smallest value pairs in a dictionary.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Previous
Next