Comparing two dictionaries in Python by identifying sets with the same key but different values

I am trying to compare two dictionaries by comparing keys, if two keys in two separate dictionaries are the same, the program should check if the values ​​are the same, if they are not the same, the program should identify that.

This is the code I wrote:

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 that were made in the previous functions).

When the code runs, it prints out all 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 will print:

'cat', 'blue'

      

while I am trying to print it:

'cat pet (animal)'

      

in this exact format.

Any advice on how to edit my code for this is appreciated :)

+3


source to share


4 answers


You can use set intersection in dictionaries keys()

. Then turn them over and check if the values ​​corresponding to these keys are identical. If not, you can print them with 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

      

+4


source


If you are using hash values, you can also use members to get common key / value pairs:

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 each one:



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

      

To find common keys with different meanings:

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

      

0


source


Using sets in your example code makes it less efficient than just looping through the keys, which is also arguably 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)

      

0


source


Well Padraic methods seem to be better than this, but this is another option. So this is not the best way, but it will get the job done.

Go 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 should print, and didn't mention that you want them to return to an array, so the above code will go through both dictates, comparing them one at a time and printing out in a format that doesn't match.

0


source







All Articles