Sort the Dictionary
Your task is to write a function called
sort_dictionary
that is capable of sorting a given dictionary either by its keys or its values.The function
sort_dictionary
takes three arguments:dictionary
: a dictionary to be sorted. The dictionary keys are strings, while values are numbers.
by
: a string that indicates whether the sorting should be performed by 'keys' or by 'values'.
reverse
: a boolean keyword-only argument that determines the sorting order. Ifreverse
isFalse
, the sorting is done in ascending order (increasing). Ifreverse
isTrue
, the sorting is done in descending order (decreasing). The default value ofreverse
should beFalse
.
The function should return the sorted dictionary as a list of tuples. Each tuple should contain two elements - the key and its corresponding value in the dictionary. The format of the tuple should be:
(key, value)
.Note that, the sorting should be case-insensitive.
Input | Output |
sort_dictionary({'Alice': 25, 'Bob': 22, 'Charlie': 27}, 'keys') | [('Alice', 25), ('Bob', 22), ('Charlie', 27)] |
sort_dictionary({'Alice': 25, 'Bob': 22, 'Charlie': 27}, 'values', reverse=True) | [('Charlie', 27), ('Alice', 25), ('Bob', 22)] |
sort_dictionary({'b': 1, 'A': 2, 'c': 3}, 'keys') | [('A', 2), ('b', 1), ('c', 3)] |
sort_dictionary({'b': 1, 'A': 2, 'c': 3}, 'values', reverse=True) | [('c', 3), ('A', 2), ('b', 1)] |
Constraints
Time limit: 2 seconds
Memory limit: 512 MB
Output limit: 1 MB