Skip to content

Instantly share code, notes, and snippets.

@FerdinaKusumah
Created December 5, 2019 01:22
Show Gist options
  • Save FerdinaKusumah/b1cf4ad7c8c39b9f94daa3a50217a63f to your computer and use it in GitHub Desktop.
Save FerdinaKusumah/b1cf4ad7c8c39b9f94daa3a50217a63f to your computer and use it in GitHub Desktop.
Sort Dictionary
"""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