Given a dictionary with list values, how can I get the number of elements where the value has a specific minimum length?
Below is my attempt:
mm = {1: [2, 5], 2: [3, 4, 7], 3: [1, 4], 4: [], 5: [1], 6: [3, 4]} item = min(mm, key=lambda f: len(mm[f]))
Expected output: 5
Advertisement
Answer
Just filter out the empty elements and pass the result to min
:
item = min((key for key, value in mm.items() if value), key=lambda k: len(mm[k]))
The inner genexpr filters to only those keys where the value is truthy (non-empty), and min
then operates only on those keys known to have non-empty values.
If you want the value itself, not the key that refers to it, this is even simpler:
min_non_empty_value = min(filter(None, mm.values()), key=len)
filter(None
is an optimized case for discarding falsy values (empty list
s in this case), and by removing the need to deal with/return a key, you can just use key=len
directly to check the length of each value.