user63898
user63898

Reputation: 30895

Python check if dict is part of other dict

i have 2 dict's with the same keys

dict1 = {'version': 222,'name_app': 'foo1'}
dict2 = {'version': 222,'name_app': 'foo1','dir': 'c','path': 'cc'}

Now I like to check if dict1 have the same keys and values as dict2 I like to avoid doing loops and check each key and value in dict1 is in dict 2 is there any pythonic elegant way to do that?
UPDATE
both keys of dict1 most be in dict 2 if only 1 match it is false

Upvotes: 3

Views: 189

Answers (3)

Harshit Garg
Harshit Garg

Reputation: 41

you can do it like this

set(dict1.items())-set(dict2.items())== set()

It will return true or false according to your condition

If dictonaries have lists:

from operator import *
g = itemgetter(*dict1)
print(dict1.keys() <= dict2.keys() and g(dict1) == g(dict2))

Upvotes: 3

Andrej Kesely
Andrej Kesely

Reputation: 195438

I'd use operator.itemgetter:

from operator import itemgetter

dict1 = {"version": 222, "name_app": "foo1"}
dict2 = {"version": 222, "name_app": "foo1", "dir": "c", "path": "cc"}

g = itemgetter(*dict1)
print(g(dict1) == g(dict2))

Prints:

True

EDIT: All keys of dict1 must be matched:

from operator import itemgetter

dict1 = {"version": 222, "name_app": "foo1"}
dict2 = {"version": 222, "name_app": "foo1", "dir": "c", "path": "cc"}

g = itemgetter(*dict1)
print(dict1.keys() <= dict2.keys() and g(dict1) == g(dict2))

Prints:

True

EDIT2: If dict has a list value:

from operator import itemgetter

dict1 = {"version": 222, "name_app": ["a", "b", "c"]}
dict2 = {"version": 222, "name_app": ["a", "b", "c"], "dir": "c", "path": "cc"}

g = itemgetter(*dict1)
print(dict1.keys() <= dict2.keys() and g(dict1) == g(dict2))

Prints:

True

Upvotes: 1

user15801675
user15801675

Reputation:

You can do this

dict1 = {'version': 222,'name_app': 'foo1'}
dict2 = {'version': 222,'name_app': 'for','dir': 'c','path': 'cc'}
common=set(dict1.items())-set(dict2.items())
print(list(common)!=[])

Upvotes: 0

Related Questions