Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: Compare Dictionaries to return keyError on missing item

I am trying to compare two dictionaries with the desired outcome being a KeyError that identifies the Key that is missing.

this is what i currently have:

d1 = {'lion': 10.0}
d2 = {'lion': 10, 'tiger': 3}

def calc_test(d1, d2):
    if set(d2) <= set(d1) == True:
        pass
    else:
        raise KeyError(set(d2))

 
calc_test(d1,d2)

if you run this though it gives the output of the entire dictionary:

KeyError: {'lion', 'tiger'}

what i'm seeking is an output that only shows the missing key:

KeyError: {'tiger'}

like image 432
Damien Wilson Avatar asked Dec 18 '25 02:12

Damien Wilson


1 Answers

If you are using set, there is a simple function called symmetric_difference for finding the uncommon values in two sets.

set(d2).symmetric_difference(set(d1))

which will give you the result: {'tiger'}

So you can modify you function like this:

d1 = {'lion': 10.0}
d2 = {'lion': 10, 'tiger': 3}

def calc_test(d1, d2):
    uncommon_items = set(d2).symmetric_difference(set(d1))
    if len(uncommon_items) > 0:
        raise KeyError(uncommon_items)

calc_test(d1, d2)
like image 142
Nitish Avatar answered Dec 20 '25 15:12

Nitish