Created
December 5, 2019 01:22
-
-
Save FerdinaKusumah/b1cf4ad7c8c39b9f94daa3a50217a63f to your computer and use it in GitHub Desktop.
Sort Dictionary
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""Sort dict by keys or values""" | |
a = dict() | |
a['banana'] = 5 | |
a['apple'] = 2 | |
a['orange'] = 3 | |
"""Before sort""" | |
print("Before sort = {}".format(a)) | |
# Before sort = {'banana': 5, 'apple': 2, 'orange': 3} | |
"""Sorted dictionary based on key""" | |
sorted_key = sorted(a.items(), key=lambda x: x[0]) | |
key_to_dict = dict(sorted_key) | |
print("Sort by key = {}".format(key_to_dict)) | |
# Sort by key = {'apple': 2, 'banana': 5, 'orange': 3} | |
"""Sorted dictionary based on value""" | |
sorted_value = sorted(a.items(), key=lambda x: x[1]) | |
val_to_dict = dict(sorted_value) | |
print("Sort by value = {}".format(val_to_dict)) | |
# Sort by value = {'apple': 2, 'orange': 3, 'banana': 5} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment