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

>>> 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

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

我的问题:

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

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


当前回答

python3:

data_set_a = dict_a.items()
data_set_b = dict_b.items()

difference_set = data_set_a ^ data_set_b

其他回答

还有一种可能,直到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))

我正在使用这个解决方案,在Python 3中完美地为我工作


import logging
log = logging.getLogger(__name__)

...

    def deep_compare(self,left, right, level=0):
        if type(left) != type(right):
            log.info("Exit 1 - Different types")
            return False

        elif type(left) is dict:
            # Dict comparison
            for key in left:
                if key not in right:
                    log.info("Exit 2 - missing {} in right".format(key))
                    return False
                else:
                    if not deep_compare(left[str(key)], right[str(key)], level +1 ):
                        log.info("Exit 3 - different children")
                        return False
            return True
        elif type(left) is list:
            # List comparison
            for key in left:
                if key not in right:
                    log.info("Exit 4 - missing {} in right".format(key))
                    return False
                else:
                    if not deep_compare(left[left.index(key)], right[right.index(key)], level +1 ):
                        log.info("Exit 5 - different children")
                        return False
            return True
        else:
            # Other comparison
            return left == right

        return False

它比较dict、list和其他单独实现“==”操作符的类型。 如果你需要比较其他不同的东西,你需要在“If树”中添加一个新的分支。

希望这能有所帮助。

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

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

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

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

我写下了这个解:

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”:['你好']}

def dict_compare(d1, d2):
    d1_keys = set(d1.keys())
    d2_keys = set(d2.keys())
    shared_keys = d1_keys.intersection(d2_keys)
    added = d1_keys - d2_keys
    removed = d2_keys - d1_keys
    modified = {o : (d1[o], d2[o]) for o in shared_keys if d1[o] != d2[o]}
    same = set(o for o in shared_keys if d1[o] == d2[o])
    return added, removed, modified, same

x = dict(a=1, b=2)
y = dict(a=2, b=2)
added, removed, modified, same = dict_compare(x, y)