Sort Python Dictionary by Values/Keys
A- create a dictionary-
items_count= {'are': 1, 'hi': 2, 'me': 3, 'you': 5}
B- Sort by values of dict -
sorted_x = sorted(items_count.items(), key=lambda kv: kv[1], reverse= True)
Sorted_x
items_count.items()- dict_item data type that items_count as tuples.
kv: kv[1] function that takes 2nd value from each tuple so that comparison happens for values not keys.
kv:kv[0] would have sorted by keys of dictionary.
C- convert list to dictionary again-
import collections sorted_dict = collections.OrderedDict(sorted_x)
creates dictionary from list to have dictionary as output data type
items_count= {'are': 1, 'hi': 2, 'me': 3, 'you': 5}
B- Sort by values of dict -
sorted_x = sorted(items_count.items(), key=lambda kv: kv[1], reverse= True)
Sorted_x
[('you', 5), ('me', 3), ('hi', 2), ('are', 1)] #op
sorted()
have a key parameter to specify a function to be called on each list element prior to making comparisons. by default ascending oreder, if reverse = True then reverse order.items_count.items()- dict_item data type that items_count as tuples.
kv: kv[1] function that takes 2nd value from each tuple so that comparison happens for values not keys.
kv:kv[0] would have sorted by keys of dictionary.
C- convert list to dictionary again-
import collections sorted_dict = collections.OrderedDict(sorted_x)
OrderedDict([('you', 5), ('me', 3), ('hi', 2), ('are', 1)]) #op
creates dictionary from list to have dictionary as output data type
Comments
Post a Comment