TechieClues TechieClues
Updated date May 31, 2021
In this code snippet, we will see how to sort a dictionary in python. In the below example we will sort a dictionary by key, value, and items.
  • 1.8k
  • 0
  • 0

In this code snippet, we will see how to sort a dictionary in python. In the below code example we will sort a dictionary by key, value, and items.

Sort by key:

dict = {}
dict['1'] = 'Ford'
dict['4'] = 'Audi'
dict['2'] = 'Toyota'
dict['3'] = 'BMW'

# Get list of keys
list = dict.keys()

# Sorted by key
print("Sorted by key: ", sorted(list))

Output:

Sorted by key:  ['1', '2', '3', '4']

Sory by value:

dict = {}
dict['1'] = 'Ford'
dict['4'] = 'Audi'
dict['2'] = 'Toyota'
dict['3'] = 'BMW'

# Get list of values
list = dict.values()

# Sorted by key
print("Sorted by value: ", sorted(list))

Output:

Sorted by value:  ['Audi', 'BMW', 'Ford', 'Toyota']

Sort by Items:

dict = {}
dict['1'] = 'Ford'
dict['4'] = 'Audi'
dict['2'] = 'Toyota'
dict['3'] = 'BMW'

// Get items
list = dict.items()

# Sorted by key
print("Sorted by key: ", sorted(list, key = lambda y : y[0]))

#Sorted by value
print("Sorted by value: ", sorted(list, key = lambda y : y[1]))

Output:

Sorted by key:  [('1', 'Ford'), ('2', 'Toyota'), ('3', 'BMW'), ('4', 'Audi')]
Sorted by value:  [('4', 'Audi'), ('3', 'BMW'), ('1', 'Ford'), ('2', 'Toyota')]

 

ABOUT THE AUTHOR

TechieClues
TechieClues

I specialize in creating and sharing insightful content encompassing various programming languages and technologies. My expertise extends to Python, PHP, Java, ... For more detailed information, please check out the user profile

https://www.techieclues.com/profile/techieclues

Comments (0)

There are no comments. Be the first to comment!!!