如何与字典相交? [英] How to intersect dictionaries?

查看:51
本文介绍了如何与字典相交?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经很长时间没有使用python了,有点生疏了,但是对于第一个问题,我正在使用字典,并且需要与它相交以返回键和值.例如,我要输入

I haven't taken python in a long time and am a bit rusty but for the first question I'm taking a dictionary and need to intersect it returning the key and the value. So for example, I'm entering

a = {1:'a1', 2.5:'a2', 4:'a3'}
b = {1:'a1', 3:'a2',  5:'a4'}

如果我输入 c = intersect(a,b),我希望它返回 {1:'a1'} ,但我只能返回{'a1'} .

If I enter c = intersect(a,b), I want it to return {1:'a1'}, but I only get back {'a1'}.

到目前为止,我的代码是:

My code so far is:

def intersect(a, b):
    for i in a:
        if j in b:
            if a[i]==b[i]:
                return ({i})
        else:
            return {}

推荐答案

您可以使用 actual set 交集来简化此操作.这仅保留共享项(键和值相同):

You could simplify this, using actual set intersection. This retains only shared items (key and value the same):

def intersect(a, b):
    return dict(set(a.items()) & set(b.items()))

如果您的 dict 参数具有不可散列的值,则可以按照以下几行进行 dict 理解:

If your dict params have non-hashable values, you can go for a dict comprehension along the following lines:

def intersect(a, b):
    return {k: a[k] for k in a if b.get(k, not a[k]) == a[k]}

您可以像这样修改原始方法:

And you can fix your original approach like so:

def intersect(a, b):
    d = {}
    for i in a:
        if i in b and a[i] == b[i]:
            d[i] = a[i]
    return d

这篇关于如何与字典相交?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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