Home > OS >  How to compare a three tiered dictionary in python and only print values that dont match
How to compare a three tiered dictionary in python and only print values that dont match

Time:08-03

I have two Dict as

RT = {'Solution 1': {'Returned Solution': 'Flight', 'Airline Class': 'Economy', 'Price': 'CAD 255.96'}, 'Solution 2': {'Returned Solution': 'Hotel', 'Hotel Name': 'Rosewood Hotel Georgia', 'Hotel Price': 'CAD 999', 'Cancellation Type': 'GUAR'}}

AA = {'Solution 1': {'Returned Solution': 'Flight', 'Airline Class': 'Main Cabin', 'Price': 'CAD 255.96'}, 'Solution 2': {'Returned Solution': 'Hotel', 'Hotel Name': 'Rosewood Hotel Georgia', 'Hotel Price': '(CAD 850   fees)'}}

I am trying to compare this nested Dict and print Value that are not same.

Expecting output as:

Airline Class : 'Economy' 'Main Cabin'
Hotel Price : 'CAD 999' '(CAD 850   fees)'
Cancellation Type: 'GUAR' 'N\A'

CodePudding user response:

RT = {'Solution 1': {'Returned Solution': 'Flight', 'Airline Class': 'Economy', 'Price': 'CAD 255.96'}, 'Solution 2': {'Returned Solution': 'Hotel', 'Hotel Name': 'Rosewood Hotel Georgia', 'Hotel Price': 'CAD 999', 'Cancellation Type': 'GUAR'}}

AA = {'Solution 1': {'Returned Solution': 'Flight', 'Airline Class': 'Main Cabin', 'Price': 'CAD 255.96'}, 'Solution 2': {'Returned Solution': 'Hotel', 'Hotel Name': 'Rosewood Hotel Georgia', 'Hotel Price': '(CAD 850   fees)'}}
ans = {}
for k,v in RT.items():
    cur = []
    for k_, v_ in v.items():
        if k_ in AA[k]:
            if (AA[k][k_]) != v_:
                cur.append(AA[k][k_])
                cur.append(v_)
                ans[k_] = cur
                cur = []
        else:
            cur.append(v_)
            cur.append("NA")
            ans[k_] = cur
            cur =[]
    
for k,v in ans.items():
    print(k, v)
  • Related