1

There is a situation where i have to find the element in a list whose corresponding value in a dictionary is minimum.

So here "boxes" is a list and "values" is a dictionary.

I have tried the following and this seems to work,

minvalue = 10
for box in boxes:
    if len(values[box]) > 1:
        if len(values[box]) < minvalue:
            minvalue = len(values[box])
            bestbox = box

But this is another way of doing the same thing but i don't get this line of code

n, s = min((len(values[s]), s) for s in boxes if len(values[s]) > 1)
Maverick
  • 19
  • 3

1 Answers1

1

What you are looking at is called List comprehensions. They are not necessarily efficient but the community prefers since it looks pythonic.

Your list comprehension typically has 3 parts :

new_list = [expression for_loop_one_or_more conditions]

So the first part you see min((len(values[s]), s) is an expression which on evaluation yields min() value.This is going to feed your for loop that follows next.

The second part is the for loop which gets its iterating value for s from the first part

Knowing this far will give you an understanding of the if condition where it compares the current iterating value of s at the index of list values

shuberman
  • 1,416
  • 6
  • 21
  • 38