sorting dictionaries if we want to do simple sort on either the keys or values of dictionarywe can do the followingnote that the first line in the preceding code sorts the keys according to alphabetical orderand the second line sorts the values in order of integer value the sorted(method has two optional arguments that are of interestkey and reverse the key argument has nothing to do with the dictionary keysbut rather is way of passing function to the sort algorithm to determine the sort order for examplein the following codewe use the __getitem__ special method to sort the dictionary keys according to the dictionary valuesessentiallywhat the preceding code is doing is for every key in to use the corresponding value to sort we can also sort the values according to the sorted order of the dictionary keys howeversince dictionaries do not have method to return key by using its valuethe equivalent of the list index method for listsusing the optional key argument to do this is little tricky an alternative approach is to use list comprehensionas the following example demonstratesthe sorted(method also has an optional reverse argumentand unsurprisinglythis does exactly what it saysreverses the order of the sorted listfor example