3
\$\begingroup\$

I created a function that takes a dictionary as parameter. This dictionary is expected to have lists as value pair. (i.e. {1: [1, 2, 3], 'a': [4, 'b', 5, 'c']} )

This function has to return the key associated to the biggest list in the dictionary, or None if the dictionary is empty. (considering the above example, it would return 'a' )

I came up with this code:

def biggest(aDict):
    return None if not aDict else [x for x in aDict if len(aDict[x]) == max(len(x) for x in aDict.values())][0]

Can I have some review on this and any ideas on how to further simplify without using external libraries?

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 1 LOC doesn't equate to good code. At the very least this shouldn't use a turnery or nested comprehensions. \$\endgroup\$
    – Peilonrayz
    Commented Jun 18, 2020 at 14:15

1 Answer 1

8
\$\begingroup\$

Your code is difficult to read:

  • The line is too long (according to the Python style guide all lines should be limited to 79 characters).
  • The same iterator variable x is used for the outer iteration and also inside the max() function.

It is also inefficient because the maximal list length is determined in each iteration.

Using the key and default argument of the max() function the same can be concisely and efficiently be implemented as

def biggest(aDict):
    return max(aDict, key=lambda k: len(aDict[k]), default=None)

More suggestions:

\$\endgroup\$
3
  • 1
    \$\begingroup\$ This is the kind of answer that I was needing! I have just started to learn python. I come from Java, so camelCase is the way to go, for me. Hehe. Also, I realize the line was big enough,but I just wanted to exploit python capabilities of one-lining all the logic, to get a better understanding of the language. \$\endgroup\$ Commented Jun 18, 2020 at 12:25
  • \$\begingroup\$ Also, would you care to explain, what the param key exactly does? Does it only accept a lambda? \$\endgroup\$ Commented Jun 18, 2020 at 12:38
  • \$\begingroup\$ @msmilkshake: It can be any function taking a single argument: a “named” function or an “anonymous” function (lambda). See also docs.python.org/3/library/functions.html#max and docs.python.org/3/library/stdtypes.html#list.sort: “key specifies a function of one argument that is used to extract a comparison key from each list element” \$\endgroup\$
    – Martin R
    Commented Jun 18, 2020 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.