本文介绍了使用其他字典过滤python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在尝试寻找一种使用另一种字典过滤字典的更pythonic的方法.目前,我有以下代码:

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

代码可以完成我想要的工作,但是我正在寻找一种更好的方法.基本上我有2本字典.data_dict是具有键值对id:response的字典,而NaN_dict是键值对id:value的字典.如果值低于公差,我希望将data_dict中具有相同ID的键值对包含在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.

我想出了类似的东西:

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!

推荐答案

我认为您几乎是正确的.似乎唯一缺少的是调用 .items()以获取键值对:

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}

这篇关于使用其他字典过滤python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-01 23:16