比较忽略特定键的词典 [英] Compare dictionaries ignoring specific keys

查看:118
本文介绍了比较忽略特定键的词典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果两个词典相等,如何考虑一些键,我该如何测试。例如,

How can I test if two dictionaries are equal while taking some keys out of consideration. For example,

equal_dicts(
    {'foo':1, 'bar':2, 'x':55, 'y': 77 },
    {'foo':1, 'bar':2, 'x':66, 'z': 88 },
    ignore_keys=('x', 'y', 'z')
)

应该返回True。

UPD:我正在寻找一个高效,快速的解决方案。

UPD: I'm looking for an efficient, fast solution.

UPD2。我最终看到这个代码是最快的:

UPD2. I ended up with this code, which appears to be the fastest:

def equal_dicts_1(a, b, ignore_keys):
    ka = set(a).difference(ignore_keys)
    kb = set(b).difference(ignore_keys)
    return ka == kb and all(a[k] == b[k] for k in ka)

计时: https://gist.github.com/2651872

推荐答案

def equal_dicts(d1, d2, ignore_keys):
    d1_filtered = dict((k, v) for k,v in d1.iteritems() if k not in ignore_keys)
    d2_filtered = dict((k, v) for k,v in d2.iteritems() if k not in ignore_keys)
    return d1_filtered == d2_filtered

编辑:这可能会更快,记忆效率更高:

This might be faster and more memory-efficient:

def equal_dicts(d1, d2, ignore_keys):
    ignored = set(ignore_keys)
    for k1, v1 in d1.iteritems():
        if k1 not in ignored and (k1 not in d2 or d2[k1] != v1):
            return False
    for k2, v2 in d2.iteritems():
        if k2 not in ignored and k2 not in d1:
            return False
    return True

这篇关于比较忽略特定键的词典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆