简体   繁体   English

通过识别具有相同键但具有不同值的集合来比较Python中的两个词典

[英]Comparing two dictionaries in Python by identifying sets with same key but different values

I'm trying to compare two dictionaries by comparing the keys, if two keys in the two seperate dictionaries are the same the program should check if the values are also the same, if they are not the same the program should identify that. 我试图通过比较键来比较两个词典,如果两个单独的词典中的两个键是相同的,程序应检查值是否也相同,如果它们不相同,程序应该识别它。

This is the code I have written: 这是我写的代码:

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' and 'seconddict' are two dictionaries which have been made in previous functions). ('firstdict'和'seconddict'是在以前的功能中制作的两个词典)。

When the code is run it prints out all the keys that are the same without their values, even if their values are different. 当代码运行时,即使它们的值不同,它也会打印出没有值的所有键。

For example if: 例如,如果:

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

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

it would print out: 它会打印出来:

'cat', 'blue'

whereas I'm tring to get it to print out: 而我想把它打印出来:

'cat pet (animal)'

in that exact format. 以那种确切的格式。

Any advice on how to edit my code to do this is appreciated :) 有关如何编辑我的代码以执行此操作的任何建议,请欣赏:)

You can use set intersection on the dictionaries keys() . 您可以在词典keys()上使用set intersection。 Then loop over those and check if the values corresponding to those keys are identical. 然后遍历这些并检查与这些键对应的值是否相同。 If not, you can print them out with format . 如果没有,您可以使用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

And for another example 而另一个例子

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

If you values are hashable also you can use items to get the common key/value pairings: 如果您的值是可清除的,您也可以使用项来获得公共键/值配对:

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

To check if both dicts are the same, check the len of each: 要检查两个dicts是否相同,请检查每个dicts:

print(len(common)) == len(firstdict)

To find common keys with different value: 要查找具有不同值的公用密钥:

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

The use of sets in your example code makes it less efficient than simply looping over the keys, which is also, perhaps, more readable: 在示例代码中使用集合使其效率低于简单地循环键,这也可能更具可读性:

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)

output: 输出:

cat animal (pet)

Well Padraic's methods seem better than this one but it is another option. Padraic的方法看起来比这个好,但它是另一种选择。 So this is not the best way but it will get the job done. 所以这不是最好的方法,但它会完成工作。

Step through each element and compare them manually. 逐步执行每个元素并手动比较它们。

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)

Your question said it was suppose to print out, and did not mention you want them returned in array so the above code will step through both dicts comparing them one by one and print out in the format the one that do not match. 你的问题说打算输出,并没有提到你希望它们在数组中返回,所以上面的代码将逐步通过两个dicts逐个比较它们并以不匹配的格式打印出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM