Extracting and altering dictionary items with 2 conditions

Question:

I have been breaking my head with this function.

def snatch(data,threshold):

Given I have the following data:

data = { 'x': [1, 2, 3, 7], 'y': [1, 3, 7, 2] }
threshold = { 'x': 3, 'y': 2 }

Briefly, the data dictionaries’ values are supposed to merge as one list, if they are above or equal to the threshold’s values.

i.e. [3,7,7,3,2] for ‘x’ 3,7 are above or equal to threshold ‘x’. And for ‘y’ 3,7,2 are above or equal to threshold ‘y.’ The mean is hence computed.

The second condition concerns the absence of a threshold. In that case, the respective letter key is excluded from the list and thus the product mean.

e.g. thresh = { 'x': 3 } hence the list from data is only [3,7]

Asked By: Kash

||

Answers:

Without computing the mean, you can just iterate over the threshold items and chain the values that meet the condition. This becomes a one-liner:

from itertools import chain

def snatch(data, threshold): return list(chain(*[[a for a in data[k] if a >= v] for k, v in threshold.items()])) 

data = {'x': [1, 2, 3, 7], 'y': [1, 3, 7, 2]}
threshold = {'x': 3, 'y': 2}

print(snatch(data, threshold))
# [3, 7, 3, 7, 2]
   

And using only some of the keys gives the required result:

thresh = {'x': 3} 
print(snatch(data, thresh))
# [3, 7]
Answered By: ShlomiF

Use a list comprehension like this:

def snatch(data, threshold):
    return [v for k in threshold for v in data[k] if v >= threshold[k]]

Essentially, the function above is doing this:

def snatch(data, threshold):
    snatched = []
    for key in threshold:
        for value in data[key]:
            if value >= threshold[key]:
                snatched.append(value)
    return snatched
Answered By: pythonista