0

I am currently using this for loop to sort a dictionary's (used as a hashmap) values in descending order, then append these keys to a list:

hashmap = {1: 2, 2: 3, 3: 1}
ans = []
for v in sorted(hashmap, key=hashmap.get, reverse=True):
    ans.append(v)

This does return me the correct answer, however I do not understand the hashmap.get call.

From what I understand the dict.get method has the required parameter keyname, and so should cause an error if none is passed. Is it that the keyword key is automatically extracting all keys from this call?

Thank you for any help.

  • 1
    `hashmap.get` doesn't call `.get`. Try `x = hashmap.get` then `print(x)`, what do you see? What is the value? – juanpa.arrivillaga Jun 14 '23 at 06:35
  • It's not so much about how `dict.get` works but rather about how `sorted` works with a `key` parameter. Yes, `dict.get` expects a parameter, but that parameter will be given to it by `sorted`. That's what `sorted` does. – Stef Jun 14 '23 at 06:42
  • Try `sorted(hashmap, key=print)` – mousetail Jun 14 '23 at 06:45

0 Answers0