How to get the difference between two dictionaries in Python?

前端 未结 9 1335
庸人自扰
庸人自扰 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 04:58

    Old question, but thought I'd share my solution anyway. Pretty simple.

    dicta_set = set(dicta.items()) # creates a set of tuples (k/v pairs)
    dictb_set = set(dictb.items())
    setdiff = dictb_set.difference(dicta_set) # any set method you want for comparisons
    for k, v in setdiff: # unpack the tuples for processing
        print(f"k/v differences = {k}: {v}")
    

    This code creates two sets of tuples representing the k/v pairs. It then uses a set method of your choosing to compare the tuples. Lastly, it unpacks the tuples (k/v pairs) for processing.

提交回复
热议问题