cduneata
11/24/2019 - 3:53 PM

Sorting dictionary by key or value

my_dict = {'g': 2, 'o': 3, 'l': 1, 'e': 1, '.': 1, 'c': 1, 'm': 1}


# dictionary.items() // returns a list of tuples with key and value from dictionary
# key = lambda x: x[1] // we sort the entire list of tuples by the second element in tuples which
#                         is the value (number) if we want to sort by key (letter) we just use 0
# reverse = True // is to reverse the entire list of tuples from the highest value to lowest
# dict() // is used to convert the list of tuples in dictionary

def sorting_by_value(dictionary):
  return dict(sorted(dictionary.items(), key = lambda x: x[1], reverse=True))
  
print(sorting_by_value(my_dict))