dict1 = {1: 1, 2: 9, 3: 4}
sorted_final = {}
sorted_keys = sorted(dict1, key=dict1.get)
for w in sorted_keys:
sorted_final[w] = dict1[w]
This code successfully sorts the dictionary dict1 by the value of each key and prints it out to a new dictionary called sorted_final. I have two questions:
I am having difficulty understanding how dict1 interacts with sorted_keys. I have not performed any operation on dict1 but I am assigning the wth element of sorted_final to the one of dict1 and sorted_final is the correctly sorted array. How is this working? I am missing the link between sorted_keys and dict1. The for loop loops over sorted_keys but other than that I do not see any relation. I'd like to understand how this works.
Is there anyway I can do this operation without creating a new dictionary, in this case - sorted_final?
Thank you!
Edit: One way I thought about while I was writing this was the fact that the for loop iterates over sorted_keys. However, I thought w here is the index of the list, not the value of what's there in wth index. For example, sorted_keys will have [1,3,2]. Does that mean the w in the for loop is 1, 3 and then 2? Or is it 0,1,2, i.e each index of sorted_keys?