Mr.President
Mr.President

Reputation: 173

Finding a key-value pair present only in the first dictionary

Two dictionaries:

dict1 = {'firstvalue':1, 'secondvalue':2, 'fourthvalue':4}
dict2 = {'firstvalue':1, 'thirdvalue':3, 'fourthvalue':5}

I get set(['secondvalue']) as a result upon doing:

dict1.viewkeys() - dict2  

I need {'secondvalue':2} as a result.
When I use set, and then do the - operation, it does not give the desired result as it consists of {'fourthvalue:4} as well.
How could I do it?

Upvotes: 2

Views: 74

Answers (4)

yatu
yatu

Reputation: 88276

IIUC and providing a solution to Finding a key-value pair present only in the first dictionary as specified, you could take a set from the key/value pairs as tuples, subtract both sets and construct a dictionary from the result:

dict(set(dict1.items()) - set(dict2.items()))
# {'fourthvalue': 4, 'secondvalue': 2}

Upvotes: 2

ncica
ncica

Reputation: 7206

Python 2.x:

dict1 = {'firstvalue':1, 'secondvalue':2, 'fourthvalue':4}
dict2 = {'firstvalue':1, 'thirdvalue':3, 'fourthvalue':5}


keys = dict1.viewkeys() - dict2.viewkeys()
print ({key:dict1[key] for key in keys})

output:

{'secondvalue': 2}

Upvotes: 0

tobias_k
tobias_k

Reputation: 82929

The problem with - is that (in this context) it is an operation of dict_keys and thus the results will have no values. Using - with viewitems() does not work, either, as those are tuples, i.e. will compare both keys and values.

Instead, you can use a conditional dictionary comprehension, keeping only those keys that do not appear in the second dictionary. Other than Counter, this also works in the more general case, where the values are not integers, and with integer values, it just checks whether a key is present irrespective of the value that is accociated with it.

>>> dict1 = {'firstvalue':1, 'secondvalue':2, 'fourthvalue':4}
>>> dict2 = {'firstvalue':1, 'thirdvalue':3, 'fourthvalue':5}
>>> {k: v for k, v in dict1.items() if k not in dict2}
{'secondvalue': 2}

Upvotes: 2

RomanPerekhrest
RomanPerekhrest

Reputation: 92874

Another simple variation with set difference:

res = {k: dict1[k] for k in dict1.keys() - dict2.keys()}

Upvotes: 1

Related Questions