Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Two different approaches to writing a function (map vs loop)

Tags:

python

SO busy with some code, and have a function which basically takes dictionary where each value is a list, and returns the key with the largest list.

I wrote the following:

def max_list(dic):
    if dic:
        l1 = dic.values()
        l1 = map(len, l1)
        l2 = dic.keys()
        return l2[l1.index(max(l1))]
    else:
        return None

Someone else wrote the following:

def max_list(dic):
    result = None
    maxValue = 0
    for key in dic.keys():
        if len(dic[key]) >= maxValue:
            result = key
            maxValue = len(dic[key])
    return result

Which would be the 'correct' way to do this, if there is one. I hope this is not regarded as community wiki (even though the code works), trying to figure which would be the best pattern in terms of the problem.

like image 445
ismail Avatar asked Jun 21 '26 07:06

ismail


2 Answers

Another valid option:

maxkey,maxvalue = max(d.items(),key=lambda x: len(x[1]))

Of the two above, I would probably prefer the explicit for loop as you don't generate all sorts of intermediate objects just to throw them away.


As a side note, This solution doesn't work particularly well for empty dicts ... (it raises a ValueError). Since I expect that is an unusual case (rather than the norm), it shouldn't hurt to enclose in a try-except ValueError block.

like image 153
mgilson Avatar answered Jun 22 '26 22:06

mgilson


the most pythonic would be max(dic,key=lambda x:len(dic[x])) ... at least I would think ...

maximizing readability and minimizing lines of code is pythonic ... usually

like image 30
Joran Beasley Avatar answered Jun 22 '26 22:06

Joran Beasley