ascending and descending order by values

 avatar
Rohit143
python
3 years ago
799 B
7
Indexable
# this will create an empty dictionary
dict1 = {1: 1, 2: 9, 3: 4}
 # Sort the values
sorted_values = sorted(dict1.values()) # 1,4,9
# this will use to store sorted dictionary
sorted_dict = {}



for i in sorted_values: #1,4,9
    for k in dict1.keys(): #1,2,3
        if dict1[k] == i: #if 1=1
            sorted_dict[k] = dict1 #this will set that key and values to the sorted_dict
            

print(sorted_dict)


# -----------------------------
reversed_values = sorted(dict1.values()) # Sort the values
new_reversed_value=reversed_values[::-1] #this will reverse the list of values

reversed_dict = {}

for i in new_reversed_value:
    for k in dict1.keys():
        if dict1[k] == i:
            reversed_dict[k] = dict1[k]
            

print(reversed_dict)

Editor is loading...