def dict_sort(_dict, _sort_by='key', _reverse=False): if _sort_by == 'key': _result = sorted(_dict.items(), key=lambda x: x[0], reverse=_reverse) else: _result = sorted(_dict.items(), key=lambda x: x[1], reverse=_reverse) _result_dict = dict() for r in _result: _result_dict[r[0]] = r[1] return _result_dict