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
x
9
1
mm = {1: [2, 5],
2
2: [3, 4, 7],
3
3: [1, 4],
4
4: [],
5
5: [1],
6
6: [3, 4]}
7
8
item = min(mm, key=lambda f: len(mm[f]))
9
Expected output: 5
Advertisement
Answer
Just filter out the empty elements and pass the result to min
:
JavaScript
1
2
1
item = min((key for key, value in mm.items() if value), key=lambda k: len(mm[k]))
2
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
1
2
1
min_non_empty_value = min(filter(None, mm.values()), key=len)
2
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.