Python: Sort a dictionary by key
Python dictionary: Exercise-14 with Solution
Write a Python program to sort a given dictionary by key
Sample Solution-1:
Python Code:
# Create a dictionary 'color_dict' with color names as keys and their corresponding color codes in hexadecimal format as values.
color_dict = {
'red': '#FF0000',
'green': '#008000',
'black': '#000000',
'white': '#FFFFFF'
}
# Iterate through the keys of the 'color_dict' dictionary after sorting them in lexicographical order.
for key in sorted(color_dict):
# Print each key-value pair where '%s' is a placeholder for the key and its associated color code.
print("%s: %s" % (key, color_dict[key]))
Sample Output:
black: #000000 green: #008000 red: #FF0000 white: #FFFFFF
Sample Solution-2:
- Use dict.items() to get a list of tuple pairs from d and sort it using sorted().
- Use dict() to convert the sorted list back to a dictionary.
- Use the reverse parameter in sorted() to sort the dictionary in reverse order, based on the second argument.
Python Code:
# Define a function 'sort_dict_by_key' that takes a dictionary 'd' and an optional 'reverse' flag.
# It returns the dictionary 'd' sorted by keys in ascending or descending order, based on the 'reverse' flag.
def sort_dict_by_key(d, reverse = False):
# Use the 'sorted' function to sort the items (key-value pairs) in the dictionary 'd' by their keys.
# The 'reverse' flag is used to specify the sorting order.
return dict(sorted(d.items(), reverse=reverse))
# Create a dictionary 'students' with keys representing names and corresponding values.
students = { 'name1': 'Theodore', 'name2': 'Mathew', 'name4': 'Roxanne', 'name3': 'David' }
# Print a message indicating the start of the code section.
print("Original dictionary:")
# Print the original dictionary 'students'.
print(students)
# Print a message indicating the start of sorting the dictionary by key in ascending order.
print("\nSort the said dictionary by key (Ascending order):")
# Call the 'sort_dict_by_key' function to sort the 'students' dictionary by key in ascending order.
# Print the result, which is the sorted dictionary.
print(sort_dict_by_key(students))
# Print a message indicating the start of sorting the dictionary by key in descending order.
print("\nSort the said dictionary by key (Descending order):")
# Call the 'sort_dict_by_key' function with 'reverse=True' to sort the 'students' dictionary by key in descending order.
# Print the result, which is the sorted dictionary in descending order by key.
print(sort_dict_by_key(students, True))
Sample Output:
Original dictionary: {'name1': 'Theodore', 'name2': 'Mathew', 'name4': 'Roxanne', 'name3': 'David'} Sort the said dictionary by key (Ascending order): {'name1': 'Theodore', 'name2': 'Mathew', 'name3': 'David', 'name4': 'Roxanne'} Sort the said dictionary by key (Descending order): {'name4': 'Roxanne', 'name3': 'David', 'name2': 'Mathew', 'name1': 'Theodore'}
Flowchart:
Python Code Editor:
Previous: Write a Python program to map two lists into a dictionary.
Next: Write a Python program to get the maximum and minimum value in a dictionary.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/dictionary/python-data-type-dictionary-exercise-14.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics