I have a dictionary of keys and lists. I'd like to iterate through the dictionary, get each list, iterate through each list and apply a condition, then append that filtered list to a new dictionary.
The function already works imperatively. Can I do the same functionally with list and dict comprehensions? The main blocker is that the wrapping dict-comp has a conditional which needs length of the list-comp.
Here it is working imperatively:
filtered_prediction_dict = {}
for prediction, confidence_intervals in prediction_dict.items():
filtered_confidence_intervals = []
for i in confidence_intervals:
if i > threshold:
filtered_confidence_intervals.append(i)
if len(filtered_confidence_intervals) >= 1:
filtered_prediction_dict[prediction] = filtered_confidence_intervals
I was wondering if I could do the same thing functionally with comprehensions, something like this:
filtered_prediction_dict = {prediction: [i for i in confidence_intervals if i > threshold] for prediction, confidence_intervals in prediction_dict.items() if len(filtered_confidence_intervals) >= 1}
Of course, python's linter points out that filtered_confidence_intervals hasn't yet been defined in len(filtered_confidence_intervals) in the conditional.
Any way around this?