Calculate difference in keys contained in two Python dictionaries

后端 未结 21 1441
眼角桃花
眼角桃花 2020-11-27 09:33

Suppose I have two Python dictionaries - dictA and dictB. I need to find out if there are any keys which are present in dictB but not

21条回答
  •  被撕碎了的回忆
    2020-11-27 10:02

    here's a solution that can compare more than two dicts:

    def diff_dict(dicts, default=None):
        diff_dict = {}
        # add 'list()' around 'd.keys()' for python 3 compatibility
        for k in set(sum([d.keys() for d in dicts], [])):
            # we can just use "values = [d.get(k, default) ..." below if 
            # we don't care that d1[k]=default and d2[k]=missing will
            # be treated as equal
            if any(k not in d for d in dicts):
                diff_dict[k] = [d.get(k, default) for d in dicts]
            else:
                values = [d[k] for d in dicts]
                if any(v != values[0] for v in values):
                    diff_dict[k] = values
        return diff_dict
    

    usage example:

    import matplotlib.pyplot as plt
    diff_dict([plt.rcParams, plt.rcParamsDefault, plt.matplotlib.rcParamsOrig])
    

提交回复
热议问题