Victor J Mytre
Victor J Mytre

Reputation: 354

In python, find the unique key-value pair or unique value with similar key

In short I have lets say 2 dictionaries of N lenght, but for the sake of example something like this:

Dict 1: {'Tomato'='ketchup', 'Apple'='juice', 'Car'='engine'}
Dict 2: {'Tomato'='mustard', 'Apple'='juice', 'Car'='engine','Airplane'='wing'}

now , I want to basically be able to retrieve first, the matching key with different values, in this case tomato:mustard so I can print out "Tomato is different, mustard is where ketchup should be" . Then after that print out "New item appeared, named Airplane containing a wing" .

For theory I know I can simply go and do for loop but I want to make sure I first check for existing keys with different values, and once all known keys from dict 1 are tested, I want to then do another for loop looking only for new keys ignoring all keys that are similar to the ones on dict 1.

I am a bit lost with python but my attempts so far have been this:

for i in dict2:
    if i not in dict1:
         print(i)

Now up until here, I can get all keys that are different and have different value. , i am printing them just to see what i am getting.

But i am lost on how to write a cleaner way to first get all keys from dict1 with different values and then after get the keys that exist in dict2 but not dict1 and their value?

Upvotes: 0

Views: 651

Answers (2)

Anorov
Anorov

Reputation: 2010

You can use set operations on the .items(), .keys(), or .values() views to be more succinct.

All keys in dict2 that are also in dict1 and have different values:

{
    k for k, v in dict2.items() - dict1.items()
    if k in dict1
}

# {'Tomato'}

All key-value pairs in dict2 for keys that are also in dict1 and have different values:

{
    k: v for k, v in dict2.items() - dict1.items()
    if k in dict1
}

# {'Tomato': 'mustard'}

All keys in dict2 that aren't in dict1:

dict2.keys() - dict1.keys()

# {'Airplane'}

All key-value pairs in dict2 for keys that aren't in dict1:

{
    k: v for k, v in dict2.items()
    if k not in dict1
}

# {'Airplane': 'wing'}

All key-value pairs in dict2 that aren't in dict1:

dict(dict2.items() - dict1.items())

# {'Airplane': 'wing', 'Tomato': 'mustard'}

Upvotes: 1

Alain T.
Alain T.

Reputation: 42129

This is the type of things you would typically do with dictionary comprehensions which can be very expressive and convey your intent better than basic for loops:

dict1 = {'Tomato':'ketchup', 'Apple':'juice', 'Car':'engine'}
dict2 = {'Tomato':'mustard', 'Apple':'juice', 'Car':'engine','Airplane':'wing'}


differences = { key:value for key,value in dict2.items() 
                          if value != dict1.get(key,value) }

print(differences) # {'Tomato': 'mustard'}

additions = { key:value for key,value in dict2.items() 
                        if key not in dict1 }

print(additions) # {'Airplane': 'wing'}

Upvotes: 1

Related Questions