Python中比较两个字典,通过确定具有相同键但不同值的集合

4
我将尝试通过比较键来比较两个字典。如果两个单独的字典中的两个键相同,则该程序应检查值是否也相同。如果它们不相同,则该程序应标识出来。
以下是我编写的代码:
def compare(firstdict,seconddict):
    shared_items = set(firstdict()) & set(seconddict())
    length = len(shared_items)
    if length > 0:
        return shared_items
    if length < 1:
        return None
print(compare(firstdict,seconddict))

('firstdict'和'seconddict'是之前函数中创建的两个字典)。

当代码运行时,它会打印出所有相同的键,而不考虑它们的值是否不同。

例如,如果:

firstdict = {'cat' : 'animal', 'blue' : 'colour', 'sun' : 'star'}

seconddict = {'cat' : 'pet', 'blue' : 'colour', 'earth' : 'star'}   

它会输出:
'cat', 'blue'

而我试图将其打印出来:
'cat pet (animal)'

任何关于如何编辑我的代码以实现这一点的建议都将不胜感激 :),请按照精确的格式进行。
4个回答

7
您可以在字典的keys()上使用集合交集。然后循环遍历它们,并检查对应于这些键的值是否相同。如果不同,您可以使用format将它们打印出来。
def compare(first, second):
    sharedKeys = set(first.keys()).intersection(second.keys())
    for key in sharedKeys:
        if first[key] != second[key]:
            print('Key: {}, Value 1: {}, Value 2: {}'.format(key, first[key], second[key]))

>>> compare(firstdict, seconddict)
Key: cat, Value 1: animal, Value 2: pet

还有一个例子

>>> firstdict = {'cat' : 'animal', 'blue' : 'colour', 'sun' : 'star', 'name': 'bob', 'shape': 'circle'}
>>> seconddict = {'cat' : 'pet', 'blue' : 'colour', 'earth' : 'star', 'name': 'steve', 'shape': 'square'}

>>> compare(firstdict, seconddict)
Key: shape, Value 1: circle, Value 2: square
Key: cat, Value 1: animal, Value 2: pet
Key: name, Value 1: bob, Value 2: steve

2
如果您的值是可哈希的,您也可以使用items来获取公共的键/值对:
firstdict = {'cat' : 'animal', 'blue' : 'colour', 'sun' : 'star'}

seconddict = {'cat' : 'pet', 'blue' : 'colour', 'earth' : 'star'}

common = set(firstdict.iteritems()).intersection(seconddict.iteritems())

for k,v in common:
    print("Key: {}, Value: {}".format(k,v))
Key: blue, Value: colour

要检查两个字典是否相同,请检查每个字典的长度:
print(len(common)) == len(firstdict)

查找具有不同值的公共键:

for k,v in firstdict.iteritems():
    if k in seconddict and seconddict[k] != v:
        print("Key: {}, Value: {}".format(k, seconddict[k]))
Key: cat, Value: pet

1

虽然这种方法不是最好的选择,但它是另一种选项。Padraic的方法似乎更好一些。所以这不是最好的方式,但可以完成工作。

逐个元素进行比较并手动检查。

def compare(dictOne,dictTwo):
    for keyOne in dictOne:
        for keyTwo in dictTwo:
            if keyTwo == keyOne:
                if dictOne[keyOne] != dictTwo[keyTwo]:
                    print(keyOne+" "+dictOne[keyOne]+" ("+dictTwo[keyTwo]+")")

compare(firstdict,seconddict)

你的问题说应该打印出来,没有提到你想要它们以数组返回,所以上面的代码将逐个比较两个字典,并按格式打印出不匹配的部分。

ekhumoro的回复可能会更加资源高效。 - Nik W

0

在您的示例代码中使用集合会使其比简单循环键的效率低下,而且可能更易读:

firstdict = {'cat' : 'animal', 'blue' : 'colour', 'sun' : 'star'}
seconddict = {'cat' : 'pet', 'blue' : 'colour', 'earth' : 'star'}

def compare(firstdict, seconddict):
    for key in firstdict:
        if key in seconddict:
            first, second = firstdict[key], seconddict[key]
            if first != second:
                print('%s %s (%s)' % (key, first, second))

compare(firstdict, seconddict)

输出:

cat animal (pet)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接