Python Forum
Getting the key for the highest value in a dict - how does this code work? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Getting the key for the highest value in a dict - how does this code work? (/thread-14348.html)



Getting the key for the highest value in a dict - how does this code work? - rogfrich - Nov-25-2018

Hi everyone.

I wrote a little script to find the most recently-modified folder inside a particular folder (on Mac OS 10.14)

Most of the code below is all my own own work, but I couldn't figure out how to get the dictionary key associated with the highest value. I went Googling, and found a solution which worked, hoping to reverse-engineer it so I'd understand - but it's baffling me. There's no question the code DOES work, but I don't understand why or how.

The relevant line in the code below is:
newest_folder = max(modified_times, key=modified_times.get) 
I've read the docs for both max() and dict.get() and I'm just not (heh) getting it. Could some kind soul explain in words of one syllable what's going on, please? Smile

The full code:

import os
# This script populates a dict with {sub-folder:time it was last modified} for all sub-folders in a given folder.
# It then finds the sub-folder with the most recent modified time
target_path = '/Volumes/Particular-path-of-interest/'  # Actual path has been redacted for posting
os.chdir(target_path)
folders = os.listdir('.')
modified_times = {}
for folder in folders:
    if os.path.isdir(folder): # MacOS puts hidden files in folders which can affect results if not filtered out
        modified_times[folder] = os.path.getmtime(folder)
# All the code above I'm fine with...
newest_folder = max(modified_times, key=modified_times.get) # This is the line I don't understand
print(newest_folder)
newest_folder returns a correctly returns a string value which is indeed the name of the most-recently modified folder.

Amongst the things I don't understand with this code is why key=modified_times.get doesn't have parentheses after the key method - the examples I've found online for dict.get() all do. I also don't understand why max() works, because the supplied parameter is a dictionary, not an iterable, and I haven't specified keys or values to iterate through.

I hate using code I don't understand, so any comments would be very welcome - I'd like to figure this out.

Thanks and kind regards,

Rich


RE: Getting the key for the highest value in a dict - how does this code work? - DeaD_EyE - Nov-26-2018

The solution is very good. It's a bit tricky.

  1. The function max takes an iterable
  2. Iterating over a dict, yields the keys. Just try: list(modified_times)
  3. For each iteration the key function is called with the key form the dict as argument. In this case the folder.
  4. Items are sorted by the return value of the key function.
  5. Every function in python is first class, because they can be passed around like any other object. First class objects in a language are handled uniformly throughout. They may be stored in data structures, passed as arguments, or used in control structures.

The function max iterates over the first element and calls then the key-function with this first element. The return value, in this case the size, is returned. All items are sorted by this returned value internally. As result you get the keys of the dictionary sorted by values.

Another example, which is easier to understand is following

list_of_strings = [...]
max(list_of_string, key=len)
Here the strings (not in example) are sorted by length.


RE: Getting the key for the highest value in a dict - how does this code work? - Larz60+ - Nov-26-2018

also, see dict.get: https://docs.python.org/3/library/stdtypes.html

Quote: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.



RE: Getting the key for the highest value in a dict - how does this code work? - rogfrich - Nov-26-2018

Hi, just a quick update - I just wanted to say thanks for the responses. Sadly a combination of work and social commitments means I won't be able to play with Python until tomorrow evening, but having read through this, I think I get it.


RE: Getting the key for the highest value in a dict - how does this code work? - rogfrich - Nov-27-2018

I've had a chance to have a play now, and I get it. :)

Thanks for the help.