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

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

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

Here’s an example:

import heapq

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

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

print(n_largest_items) # [('K', 8), ('B', 4), ('A', 3)]

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

The heapq.nlargest() 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.nlargest() will return all items that have the same value as the nth largest value.

Tags: