Filtering a python dictionary using another dictionary

回眸只為那壹抹淺笑 提交于 2021-01-29 01:57:39

问题


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!


回答1:


I think you are almost right. Seems that the only thing missing is to call .items() for getting key-value pairs:

{k: v for k, v in data_dict.items() if NaN_dict[k] <= tolerance}


来源:https://stackoverflow.com/questions/33358933/filtering-a-python-dictionary-using-another-dictionary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!