It was just the wrong index. Use index 0 if you want to sort by keys and if you use 1, you're sorting by values.
If you sort by keys, you should get this order:
Predefined order:
But I hope it helps to clarify that you can do also custom sort order.
If you sort by keys, you should get this order:
In [45]: sorted("precise clever talented bright smart exact".split()) Out[45]: ['bright', 'clever', 'exact', 'precise', 'smart', 'talented']For example, you can sort your
str
also by length:In [46]: sorted("precise clever talented bright smart exact".split(), key=len) Out[46]: ['smart', 'exact', 'clever', 'bright', 'precise', 'talented']Now back to your code:
def reverse_dictionary(input_dict): my_dict= {} for key, value in input_dict.items(): for string in value: my_dict.setdefault(string.lower(), []).append(key.lower()) output_dict={k:v for k,v in sorted(my_dict.items(), key=lambda item:item[0])} # not index 1, index 0 is the key return output_dict # first iteration from operator import itemgetter def reverse_dictionary(input_dict): result = {} by_key = itemgetter(0) for key, values in input_dict.items(): for string in values: result.setdefault(string.lower(), []).append(key.lower()) return dict(sorted(result.items(), key=by_key)) # second iteration from collections import defaultdict from operator import itemgetter def reverse_dictionary(input_dict): result = defaultdict(list) by_key = itemgetter(0) for key, values in input_dict.items(): for string in values: result[string.lower()].append(key.lower()) return dict(sorted(result.items(), key=by_key)) # third iteration from collections import defaultdict from operator import itemgetter def sort_dict_keys(mapping): return dict(sorted(result.items(), key=itemgetter(0))) def reverse_dictionary(input_dict): result = defaultdict(list) for key, values in input_dict.items(): for string in values: result[string.lower()].append(key.lower()) return sort_dict_keys(result)If you have a predefined order, you could use a mapping to
int
.Predefined order:
def custom_order(key_value, default=0): key, _ = key_value key_order = { "bright": 1, "clever": 2, "exact": 100, "precise": 3, "smart": 4, "talented": 5, } return key_order.get(key, default)It's not the best example because the dict was defined inside the function.
But I hope it helps to clarify that you can do also custom sort order.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!