compare two dictionaries in python
Question: How do i campare dictionaries that contain dictionaries ?

This will work in case the dictionaries contain simple values

    
    
    # will show the keys with different values
    
    d1_keys = set(dict1.keys())
    d2_keys = set(dict2.keys())
    intersect_keys = d1_keys.intersection(d2_keys)
    modified = {}
    for i in intersect_keys:
         if dict1[i] != dict2[i] : modified.update({i : (dict1[i], dict2[i])})
    

but i have a dictionary like this:

    
    
    { 'medic1' : {'date' : '02/02/2015', 'no' : '123' }, 'medic2' : {'date' :'02/03/2015', 'no' : '456' }}
    


Answer: By recursion function for nested dictionary.

  1. Get common keys from both dictionary by `keys()` and `set operation.`
  2. Iterate common keys by `for` loop.
  3. Check `type` of value of key is `dict` or not.
  4. If value type is `dict` then call same function and pass values dictionary as arguments. and add result as key into `modified` dictionary. 
  5. If value type is not dict then add into `modified` dictionary. 

code:

    
    
    dict1 = { 
            'medic1' : {'date' : '02/02/2015', 'no' : '123' }, 
            'medic2' : {'date' : '02/03/2015', 'no' : '456' },
            'testkey1': 'testvalue1',
            'testkey2': 'testvalue2',
            'testkey3':{ "level2_1":"value2_1", 
                "level2_2":{ 
                            "level3_1": "value3_1_change", 
                            "level3_2": "value3_2", 
                        }
            }
    }
    
    dict2 = { 
            'medic1' : {'date' : '02/02/2015', 'no' : '456' }, 
            'medic2' : {'date' : '02/03/2015', 'no' : '456' },
            'testkey1': 'testvalue1',
            'testkey2': 'testvalue22',
            'testkey3':{ "level2_1":"value2_1", 
                        "level2_2":{ 
                                    "level3_1": "value3_1", 
                                    "level3_2": "value3_2", 
                                }
                    }
    
    }
    
    import copy
    
    def compareDict(dict1, dict2):
    
        d1_keys = dict1.keys()
        d2_keys = dict2.keys()
        intersect_keys = set(d1_keys).intersection(set(d2_keys))
        modified = {}
        for i in intersect_keys:
            if dict1[i] != dict2[i] : 
                if isinstance(dict1[i], dict) and isinstance(dict1[i], dict):
                    modified[i]=compareDict(dict1[i], dict2[i])
                else:
                    modified.update({i : (dict1[i], dict2[i])})
    
        return copy.deepcopy(modified)
    
    
    modified = compareDict(dict1, dict2)
    import pprint
    pprint.pprint(modified)
    

output:

    
    
    vivek@vivek:~/Desktop/stackoverflow$ python 5.py 
    {'medic1': {'no': ('123', '456')},
     'testkey2': ('testvalue2', 'testvalue22'),
     'testkey3': {'level2_2': {'level3_1': ('value3_1_change', 'value3_1')}}}
    

