Python Forum
Getting the key for the highest value in a dict - how does this code work?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Getting the key for the highest value in a dict - how does this code work?
#1
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
Reply
#2
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#3
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.
Reply
#4
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.
Reply
#5
I've had a chance to have a play now, and I get it. :)

Thanks for the help.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  hi need help to make this code work correctly atulkul1985 5 702 Nov-20-2023, 04:38 PM
Last Post: deanhystad
  newbie question - can't make code work tronic72 2 626 Oct-22-2023, 09:08 PM
Last Post: tronic72
  Beginner: Code not work when longer list raiviscoding 2 765 May-19-2023, 11:19 AM
Last Post: deanhystad
  Why doesn't this code work? What is wrong with path? Melcu54 7 1,681 Jan-29-2023, 06:24 PM
Last Post: Melcu54
  Code used to work 100%, now sometimes works! muzicman0 5 1,384 Jan-13-2023, 05:09 PM
Last Post: muzicman0
  color code doesn't work harryvl 1 842 Dec-29-2022, 08:59 PM
Last Post: deanhystad
  Something the code dont work AlexPython 13 2,129 Oct-17-2022, 08:34 PM
Last Post: AlexPython
  Read directory listing of files and parse out the highest number? cubangt 5 2,254 Sep-28-2022, 10:15 PM
Last Post: Larz60+
  cannot get code to work Led_Zeppelin 10 2,315 Jun-30-2022, 06:28 PM
Last Post: deanhystad
  How does this code work? pd_minh12 3 1,295 Apr-15-2022, 02:50 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020