Created
July 28, 2020 13:34
-
-
Save FerdinaKusumah/dd6d5e594f7512e8b7f5939538d25a37 to your computer and use it in GitHub Desktop.
[Python] 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 dictionary by key or value""" | |
fruits = dict() | |
fruits["apple"] = 3 | |
fruits["banana"] = 2 | |
fruits["mango"] = 5 | |
"""Sort by key""" | |
sort_key = sorted(fruits.items(), key=lambda f: f[0]) | |
print(f'Sort by key = {dict(sort_key)}') | |
# Sort by key = {'apple': 3, 'banana': 2, 'mango': 5} | |
"""Sort by value""" | |
sort_value = sorted(fruits.items(), key=lambda f: f[1]) | |
print(f'Sort by value = {dict(sort_value)}') | |
# Sort by value = {'banana': 2, 'apple': 3, 'mango': 5} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment