How to get the n smallest items in a Python dictionary?

Published on Aug. 22, 2023, 12:17 p.m.

To get the n smallest items (key-value pairs with the lowest values) in a Python dictionary, you can use the heapq.nsmallest() function.

Here’s an example:

import heapq

my_dict = {'A': 3, 'B': 4, 'H': 1, 'K': -2, 'T': 0}

n_smallest_items = heapq.nsmallest(3, my_dict.items(), key=lambda x: x[1])

print(n_smallest_items) # [('K', -2), ('H', 1), ('T', 0)]

This will print the three key-value pairs with the lowest values in the dictionary, sorted in ascending order of values.

The heapq.nsmallest() function takes three arguments: n (the number of items you want to retrieve), iterable (the dictionary as an iterable of key-value pairs), and key (a function that takes an item and returns the value used to compare items). In this example, the key argument is a lambda function that returns the second element of the tuple (the value).

Note that if there are ties, heapq.nsmallest() will return all items that have the same value as the nth smallest value.

Tags: