Issue
What does the following syntax do differently than simply sorting the list without a key? MYDICT
is a dictionary
sorted(MYDICT, key = MYDICT.get)
Solution
This is a short way of sort dict
keys by value. Here is why:
mydict = {"a": 3, "b": 2, "c": 1}
sorted(mydict, key=mydict.get)
Output is:
['c', 'b', 'a']
The reason is that the key=
argument to sorted()
is expecting a callable function that takes the current list item as the argument and returns the value to use to sort that item with.
In the above case, mydict.get(key)
will return the value of key
.
When you iterate over a dict
, it only iterates over the keys, not the values.
Putting it all together, sorted(mydict)
is iterating over and returning a list containing the sorted keys of mydict, but using mydict.get(key)
, which returns the value of that key, to do the sorting with.
Answered By - gahooa
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.