Calculate difference in keys contained in two Python dictionaries

后端 未结 21 1453
眼角桃花
眼角桃花 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 you really mean exactly what you say (that you only need to find out IF "there are any keys" in B and not in A, not WHICH ONES might those be if any), the fastest way should be:

    if any(True for k in dictB if k not in dictA): ...
    

    If you actually need to find out WHICH KEYS, if any, are in B and not in A, and not just "IF" there are such keys, then existing answers are quite appropriate (but I do suggest more precision in future questions if that's indeed what you mean;-).

提交回复
热议问题