codiearcher
codiearcher

Reputation: 403

Python - Compare two dictionaries, create a new dictionary of unique items which occur only in one dictionary

Say I have two dictionaries:

dict_one = {abc: 5, bat: 1, car: 6, xray: 3}
dict_two = {abc: 2, jfk: 4, zit: 7}

I want to compare the keys of both and create a new dictionary which contains only the keys of dict_one which don't occur in dict_two.

The new dictionary would look like this:

unique_dict = {bat: 1, car: 6, xray: 3}

This is what I am trying at the moment (the first part found here: Python read two dictionaries compare values and create third dictionary)

However I know the problem is that I can't update(key, value) as it takes only one argument, but I just don't know how to do this correctly.

d1_values = set(dict_one.keys())
d2_values = set(dict_two.keys())
words_in_both = d1_values & d2_values
not_in_both = d1_values ^ d2_values

unique_dict = {}
for key, value in dict_one.items():
    for word in words_in_both:
        if key != word:
    unique_dict.update(key, value) # this is not correct

Upvotes: 0

Views: 143

Answers (3)

user11676515
user11676515

Reputation:

def filter_dicts(d1, d2):
    """Return d1 items that are not in d2"""
    return {title: value for title, value in d1.items() if title not in d2}

Upvotes: 1

ShadowRanger
ShadowRanger

Reputation: 155428

Sets and dict views already support subtraction to keep only the values in the left hand side not found in the right. So your code could simplify to:

{k: dict_one[k] for k in dict_one.keys() - dict_two.keys()}

yatu's answer is probably better in this specific case (no set temporary required), but I figured I'd point out set/view subtraction as well as showing no conversion to set itself is necessary (views can be used as set-like objects already).

Upvotes: 1

yatu
yatu

Reputation: 88236

You could use the following dictionary comprehension to keep the key/value pairs in dict_one if they are not in dict_two:

{k:v for k,v in dict_one.items() if k not in dict_two}
# {'bat': 1, 'car': 6, 'xray': 3}

Upvotes: 2

Related Questions