Skip to content Skip to sidebar Skip to footer

How To Intersect Dictionaries?

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

Solution 1:

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

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

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

Solution 2:

Here is a version of the intersect function, that intersects the keys and uses the values of the first dictionary, that means in case of different values, this function is biased towards the value in the first dictionary:

def intersect(a, b):
    return {k: a[k] for k in a.keys() & b.keys()}

This works because, the dict_keys view objects returned by dict.keys() (since Python 3) are sets (i.e. implement collections.abc.Set).

If you want to customize, which value will be used, we can use a function, that takes both values:

def intersect(a, b, select=lambda a, b: a):
    return {k: select(a[k], b[k]) for k in a.keys() & b.keys()}

Instead of returning one of the values, we could then also e.g. add the values:

>>> intersect({'a': 4, 'b': 3}, {'a': 5}, lambda a, b: a + b)
{'a': 9}

Post a Comment for "How To Intersect Dictionaries?"