我有两本字典,但为了简化起见,我就选这两本:

>>> x = dict(a=1, b=2)
>>> y = dict(a=2, b=2)

现在,我想比较x中的每个键值对在y中是否有相同的对应值,所以我这样写:

>>> for x_values, y_values in zip(x.iteritems(), y.iteritems()):
        if x_values == y_values:
            print 'Ok', x_values, y_values
        else:
            print 'Not', x_values, y_values

它的工作原理是返回一个元组,然后比较是否相等。

我的问题:

这对吗?还有更好的办法吗?最好不是在速度上,我说的是代码优雅。

更新:我忘了提到,我必须检查有多少键,值对是相等的。


当前回答

还有一种可能,直到OP的最后一个音符,是比较转储为JSON的字典的哈希值(SHA或MD)。构造哈希的方式保证如果它们相等,源字符串也相等。这是非常快速和数学上合理的。

import json
import hashlib

def hash_dict(d):
    return hashlib.sha1(json.dumps(d, sort_keys=True)).hexdigest()

x = dict(a=1, b=2)
y = dict(a=2, b=2)
z = dict(a=1, b=2)

print(hash_dict(x) == hash_dict(y))
print(hash_dict(x) == hash_dict(z))

其他回答

>>> x = {'a':1,'b':2,'c':3}
>>> x
{'a': 1, 'b': 2, 'c': 3}

>>> y = {'a':2,'b':4,'c':3}
>>> y
{'a': 2, 'b': 4, 'c': 3}

METHOD 1:

>>> common_item = x.items()&y.items() #using union,x.item() 
>>> common_item
{('c', 3)}

METHOD 2:

 >>> for i in x.items():
        if i in y.items():
           print('true')
        else:
           print('false')


false
false
true

我有一个默认/模板字典,我想从第二个给定的字典更新它的值。因此,更新将发生在默认字典中存在的键以及相关值与默认键/值类型兼容的键上。

在某种程度上,这与上面的问题类似。

我写下了这个解:

CODE

def compDict(gDict, dDict):

    gDictKeys = list(gDict.keys())
    
    for gDictKey in gDictKeys: 
        try:
            dDict[gDictKey]
        except KeyError:
            # Do the operation you wanted to do for "key not present in dict".
            print(f'\nkey \'{gDictKey}\' does not exist! Dictionary key/value no set !!!\n')
        else:
            # check on type
            if type(gDict[gDictKey]) == type(dDict[gDictKey]):
                if type(dDict[gDictKey])==dict:
                    compDict(gDict[gDictKey],dDict[gDictKey])
                else:
                    dDict[gDictKey] = gDict[gDictKey]
                    print('\n',dDict, 'update successful !!!\n')
            else:
               print(f'\nValue \'{gDict[gDictKey]}\' for \'{gDictKey}\' not a compatible data type !!!\n')
            

# default dictionary
dDict = {'A':str(),
        'B':{'Ba':int(),'Bb':float()},
        'C':list(),
        }

# given dictionary
gDict = {'A':1234, 'a':'addio', 'C':['HELLO'], 'B':{'Ba':3,'Bb':'wrong'}}

compDict(gDict, dDict)

print('Updated default dictionry: ',dDict)

输出

“A”的值“1234”不是兼容的数据类型!!

键“a”不存在!字典键/值没有设置!!

{A: ", " B ":{“Ba”:0,“Bb”:0.0},“C”:['你好']}更新成功! !

{'Ba': 3, 'Bb': 0.0}更新成功!!

“Bb”的值“错误”不是兼容的数据类型!!

更新默认dictionry: {A:“B:{“Ba”:3,“Bb”:0.0},“C”:['你好']}

参见字典视图对象: https://docs.python.org/2/library/stdtypes.html#dict

这样你可以从dictView1中减去dictView2,它将返回一组在dictView2中不同的键/值对:

original = {'one':1,'two':2,'ACTION':'ADD'}
originalView=original.viewitems()
updatedDict = {'one':1,'two':2,'ACTION':'REPLACE'}
updatedDictView=updatedDict.viewitems()
delta=original | updatedDict
print delta
>>set([('ACTION', 'REPLACE')])

你可以交叉,并,差(如上所示),对称差这些字典视图对象。 更好吗?更快呢?-不确定,但它是标准库的一部分-这使得它在可移植性方面有很大的优势

在Python 3.6中,可以这样做:-

if (len(dict_1)==len(dict_2): 
  for i in dict_1.items():
        ret=bool(i in dict_2.items())

如果dict_1中的所有项都出现在dict_2中,Ret变量将为真

你可以用下面的方法写出你自己的函数。

class Solution:
    def find_if_dict_equal(self,dict1,dict2):
        dict1_keys=list(dict1.keys())
        dict2_keys=list(dict2.keys())
        if len(dict1_keys)!=len(dict2_keys):
            return False
        for i in dict1_keys:
            if i not in dict2 or dict2[i]!=dict1[i]:
                return False
        return True
        
    def findAnagrams(self, s, p):
        if len(s)<len(p):
            return []
        p_dict={}
        for i in p:
            if i not in p_dict:
                p_dict[i]=0
            p_dict[i]+=1
        s_dict={}
        final_list=[]
        for i in s[:len(p)]:
            if i not in s_dict:
                s_dict[i]=0
            s_dict[i]+=1
        if self.find_if_dict_equal(s_dict,p_dict):
            final_list.append(0)
        for i in range(len(p),len(s)):
            element_to_add=s[i]
            element_to_remove=s[i-len(p)]
            if element_to_add not in s_dict:
                s_dict[element_to_add]=0
            s_dict[element_to_add]+=1
            s_dict[element_to_remove]-=1
            if s_dict[element_to_remove]==0:
                del s_dict[element_to_remove]
            if self.find_if_dict_equal(s_dict,p_dict):
                final_list.append(i-len(p)+1)
        return final_list