Predictive Hacks

How to Sort a Dictionary by Values

Assume that we have the following dictionary and we want to sort it by values (assume that the values are numeric data type).

d={"a":3,"b":5,"c":2}

# sort it by value
dict(sorted(d.items(), key=lambda item: item[1]))
{'c': 2, 'a': 3, 'b': 5}

If we want to sort it in descending order:

dict(sorted(d.items(), key=lambda item: item[1], reverse=True))
{'b': 5, 'a': 3, 'c': 2}

Finally, if we want to get the first n keys:

n = 2
dict(sorted(d.items(), key=lambda item: item[1])[0:n])
{'c': 2, 'a': 3}

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.

Python

Intro to Chatbots with HuggingFace

In this tutorial, we will show you how to use the Transformers library from HuggingFace to build chatbot pipelines. Let’s