dict1 = {1: 1, 2: 9, 3: 4} sorted_dict = {} sorted_keys = sorted(dict1, key=dict1.get) # [1, 3, 2] for w in sorted_keys: sorted_dict[w] = dict1[w] print(sorted_dict) # {1: 1, 3: 4, 2: 9}
Here is what the above code is Doing:
1. We create a new dictionary called sorted_dict.
2. We create a list called sorted_keys. This list contains the keys of dict1 sorted by their values.
3. We iterate through sorted_keys and add each key-value pair to sorted_dict.