How to get the difference between two dictionaries in Python?

前端 未结 9 1359
庸人自扰
庸人自扰 2020-11-27 04:45

I have two dictionaries. I need to find the difference between the two which should give me both key and value.

I have searched and found some addons/packages like d

9条回答
  •  误落风尘
    2020-11-27 05:20

    This function gives you all the diffs (and what stayed the same) based on the dictionary keys only. It also highlights some nice Dict comprehension, Set operations and python 3.6 type annotations :)

    from typing import Dict, Any, Tuple
    def get_dict_diffs(a: Dict[str, Any], b: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any], Dict[str, Any], Dict[str, Any]]:
    
        added_to_b_dict: Dict[str, Any] = {k: b[k] for k in set(b) - set(a)}
        removed_from_a_dict: Dict[str, Any] = {k: a[k] for k in set(a) - set(b)}
        common_dict_a: Dict[str, Any] = {k: a[k] for k in set(a) & set(b)}
        common_dict_b: Dict[str, Any] = {k: b[k] for k in set(a) & set(b)}
        return added_to_b_dict, removed_from_a_dict, common_dict_a, common_dict_b
    

    If you want to compare the dictionary values:

    values_in_b_not_a_dict = {k : b[k] for k, _ in set(b.items()) - set(a.items())}
    

提交回复
热议问题