Calculate difference in keys contained in two Python dictionaries

后端 未结 21 1462
眼角桃花
眼角桃花 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 09:58

    As Alex Martelli wrote, if you simply want to check if any key in B is not in A, any(True for k in dictB if k not in dictA) would be the way to go.

    To find the keys that are missing:

    diff = set(dictB)-set(dictA) #sets
    
    C:\Dokumente und Einstellungen\thc>python -m timeit -s "dictA =    
    dict(zip(range(1000),range
    (1000))); dictB = dict(zip(range(0,2000,2),range(1000)))" "diff=set(dictB)-set(dictA)"
    10000 loops, best of 3: 107 usec per loop
    
    diff = [ k for k in dictB if k not in dictA ] #lc
    
    C:\Dokumente und Einstellungen\thc>python -m timeit -s "dictA = 
    dict(zip(range(1000),range
    (1000))); dictB = dict(zip(range(0,2000,2),range(1000)))" "diff=[ k for k in dictB if
    k not in dictA ]"
    10000 loops, best of 3: 95.9 usec per loop
    

    So those two solutions are pretty much the same speed.

提交回复
热议问题