I am currently trying to find a more pythonic way of filtering a dictionary using another dictionary. Currently I have the following code:
def filter_respondents(data_dict, tolerance):
NaN_dict = diagnostic_tools.get_NaN_ratio(data_dict)
final_dict = {}
for respondent in data_dict:
if NaN_dict[respondent]<=tolerance:
final_dict[respondent] = data_dict[respondent]
return final_dict
The code does what I want it to do but I'm looking for a better way of doing it. Basically I have 2 dictionaries. data_dict is a dictionary with the key-value pairs id:response and NaN_dict has the key-value pairs id:value. If value is below tolerance, I want the key-value pair with the same ID in data_dict to be included in final_dict.
I came up with something like:
final_dict = {k:v for k,v in data_dict if NaN_dict[k]<=tolerance}
Which I know is wrong, but I'm not sure how to proceed. Thanks!