Home > Blockchain >  python: Compare Dictionaries to return keyError on missing item
python: Compare Dictionaries to return keyError on missing item

Time:05-05

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'}

CodePudding user response:

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)

CodePudding user response:

Try difference:

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).difference(set(d1)))

 
calc_test(d1,d2)

CodePudding user response:

Just check the keys in d2 are in d1:

def calc_test(d1, d2):
    s = []
    for i in d2:
        if i not in d1:
            s.append(i)
    if s:
        raise(KeyError(s))
# Raises
KeyError: ['tiger']

Note that this will not work if there is a key in d1 that is not in d2

Although it's larger in length, it's efficient in time and space complexity.

CodePudding user response:

Use the difference operator, set(d2)-set(d1).

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)-set(d1))

try:
    calc_test(d1,d2)
except Exception as e:
    print(e)

This will show the keys in d2 that are not in d1.

  • Related