Compare two dicts containing lists and return removed items

Question:

I am comparing two dicts to get removed (not changed) items.

Minimal example:

prev = {'HOST_A': [['OS_TYPE', 'AIX'], ['HAS_COBOL', '0'], ['HAS_TUXEDO', '0'], ['IP', '10.111.160.68'], ['IP', '10.111.160.66'], ['IP', '10.95.0.112']]}

current = {'HOST_A': [['OS_TYPE', 'LINUX'], ['HAS_COBOL', '0'], ['HAS_TUXEDO', '1']]}


# return a dict that contains what is missing in current data
def get_deleted(a, b):
    answer = {}
    for ki, vi in a.items():
        try:
            vd = b[ki]
        except KeyError:
            continue
        ls_del = [i for i in vi if i not in vd]
        answer[ki] = {}
        answer[ki] = ls_del
    return answer



b = get_deleted(prev, current)
print('result dict:', b)

for k, v in b.items():
    if isinstance(v, list):
        isize = len(v)
        for value in v:
            # print(isize)
            if isize >= 1:
                print(k, value[0].rstrip(), value[1].rstrip())

Output:

result dict: {'HOST_A': [['OS_TYPE', 'AIX'], ['HAS_TUXEDO', '0'], ['IP', '10.111.160.68'], ['IP', '10.111.160.66'], ['IP', '10.95.0.112']]}
HOST_A OS_TYPE AIX
HOST_A HAS_TUXEDO 0
HOST_A IP 10.111.160.68
HOST_A IP 10.111.160.66
HOST_A IP 10.95.0.112

Expected output:

result dict: {'HOST_A': [['IP', '10.111.160.68'], ['IP', '10.111.160.66'], ['IP', '10.95.0.112']]}
HOST_A IP 10.111.160.68
HOST_A IP 10.111.160.66
HOST_A IP 10.95.0.112

How to modify the get_deleted function to get the expected output?
Code examples only with Python standard library, no external modules possible.

Asked By: flynn1973

||

Answers:

You are comparing the entire list, and ['HAS_TUXEDO', '0'] is not equal to ['HAS_TUXEDO', '1']. You need to compare the zeroth element of each.

def get_deleted(a, b):
    answer = {}
    for ki, vi in a.items():
        try:
            vd = [k[0] for k in b[ki]]
        except KeyError:
            continue
        ls_del = [i for i in vi if i[0] not in vd]
        answer[ki] = ls_del
    return answer

It would probably be an improvement to use more descriptive variable names (and ls_del seems redundant: just assign answer[ki] = [i for i ...]).

Answered By: tripleee
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.