0
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:

  1. 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.

  2. 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?

  • Take a look at [How do I sort a dictionary by value?](https://stackoverflow.com/q/613183/674039) – wim Oct 13 '22 at 04:08
  • @wim, I did. My question is deeper and different from what's being asked there. – winterlyrock Oct 13 '22 at 04:15
  • 3
    Yeah, that's why I didn't dupe close. AFAIK there's no _efficient_ way to do it without creating a new dictionary, but for most practical purposes rebinding the same name to the new dict like `dict1 = {k: dict1[k] for k in sorted(dict1, key=dict1.get)}` is just as good. – wim Oct 13 '22 at 04:17
  • `sorted_keys` is a list, and you are iterating through each item in the list (not the index). If you want to explore the object, just add a few print statements, like `print(w)` or `print(type(sorted_keys))` – bn_ln Oct 13 '22 at 05:12

0 Answers0