Skip to content
Advertisement

How to get minimum length of a sublist from dictionary except zero? [closed]

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:

JavaScript

Expected output: 5

Advertisement

Answer

Just filter out the empty elements and pass the result to min:

JavaScript

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:

JavaScript

filter(None is an optimized case for discarding falsy values (empty lists 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.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement