Calculate difference in keys contained in two Python dictionaries

后端 未结 21 1454
眼角桃花
眼角桃花 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条回答
  •  旧时难觅i
    2020-11-27 09:40

    If on Python ≥ 2.7:

    # update different values in dictB
    # I would assume only dictA should be updated,
    # but the question specifies otherwise
    
    for k in dictA.viewkeys() & dictB.viewkeys():
        if dictA[k] != dictB[k]:
            dictB[k]= dictA[k]
    
    # add missing keys to dictA
    
    dictA.update( (k,dictB[k]) for k in dictB.viewkeys() - dictA.viewkeys() )
    

提交回复
热议问题