Write a Python Program to Sort a Dictionary by Value

Python Program to Sort a Dictionary by Value

Welcome to the World of Online Learning:

Hello Friends “This blog helps you to learn  Python programming concepts. You can learn Python language at your own speed and time. One can learn concepts of Python language by practicing various programs given on various pages of this blog. Enjoy the power of Self-learning using the Internet.”

Python Program to Sort a Dictionary by Value
Python Program to Sort a Dictionary by Value

Write a Python Program to Sort a Dictionary by Value

PROGRAM: Python Program to Sort a Dictionary by Value

/* Python Program to Sort a Dictionary by Value */

1: Sort the dictionary based on values

dt = {5:4, 1:6, 6:3}

sorted_dt = {key: value for key, value in sorted(dt.items(), key=lambda item: item[1])}

print(sorted_dt)
Output
{6: 3, 5: 4, 1: 6}

2: Sort only the values

dt = {5:4, 1:6, 6:3}

sorted_dt_value = sorted(dt.values())
print(sorted_dt_value)

Output

[3, 4, 6]
 

Leave a Reply

Your email address will not be published. Required fields are marked *