I was reading this really helpful SO post on sorting dictionaries. One of the most popular answers suggests this:
sorted(dict1, key=dict1.get)
While this seems to work perfectly fine, I don't get the key=dict1.get part.
What exactly is get here and what does it do?
I am only familiar with using get('X') to extract X from a dictionary...
And I couldn't find anything in the docs on dictionaries and stdtypes, so any pointers are much appreciated!
NB here is what they have to say about get(), or is this something entirely different?
Thanks!
get(key[, default]) Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError
.getinvoked on a dictionary does, that's what's being called for each key in the dictionary.sorted(with itskeyargument) anddict.get, I don't know what else is left to explain.get, consider reading the doc forsorted, and while you are at it, why not look at the doc for the parameterkeyof thesortedfunction?