pythonfor-loopminunpack

How to: for loop minimum value dictionary python?


I have a problem with creating a tuple with a minimum value from a dictionary. I found a way with the lambda function but my teacher says that I need to create a for loop where i "unpack" the dictionary, find the minimum value of the dictionary, and return it.

I'm lost, this is what I have now but I need to change the fastest_travel_mode(distance):

travel_times = {"Walk": (2, 5, 0),
                "Bike": (4, 18, 3),
                "Bus": (8, 35, 8)}


def travel_time_per_mode(distance):
    fastest_times = {}
    for mode in travel_times:
        setup_time, speed, finish_time = travel_times[mode]
        fastest_times[mode] = setup_time + 60 / speed * distance + finish_time
    return fastest_times


def fastest_travel_mode(distance):
    travel_time = travel_time_per_mode(distance)
    for fastest_mode in sorted(travel_time.items(), key=lambda kv: kv[1]):
        return fastest_mode


def main():
    distance = float(input("How many kilometers do you have to travel? "))
    print("When you have to travel", distance, "km, taking a", fastest_travel_mode(distance)[0], "will be the quickest way to your destination with an approximate time of", int(fastest_travel_mode(distance)[1]), "minutes.")


if __name__ == "__main__":
    main()




I tried:

def fastest_travel_mode(distance):
    travel_time = travel_time_per_mode(distance)
    for fastest_mode in sorted(travel_time.items(), key=lambda kv: kv[1]):
        return fastest_mode

It works but i need to do it another way including the steps creating a for loop "unpack" the dictionary, find the minimum value of the dictionary, and return it.


Solution

  • You can use min method. By default it searches minimum by looking at dict keys, but you can provide key argument to search by something else. In that case we use get function which tells find the key with minimum value

    def fastest_travel_mode(distance):
        travel_time = travel_time_per_mode(distance)
        mode = min(travel_time, key=travel_time.get)
        return mode, travel_time[mode]
    

    And now you do the calculation twice, you can do it once and store the result:

    def main():
        distance = float(input("How many kilometers do you have to travel? "))
        mode, time = fastest_travel_mode(distance)
        ...