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'}
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With