user2406718 user2406718 - 4 months ago 11
Python Question

python how to find if a dictionary contains data from other dictionary

In Python, how do i find if a dictionary contains data from the other dictionary.

my data is assigned to a variable like this

childDict = {
"assignee" : {
"first":"myFirstName",
"last":"myLastName"
},
"status" : "alive"
}


I have another dictionary named masterDict with similar hierarchy but with some more data in it.

masterDict = {
"description": "sample description"
"assignee" : {
"first":"myFirstName",
"last":"myLastName"
},
"status" : "dead"
"identity": 1234
}


Now I need to read through childDict and find out if masterDict has these values in them or not.

data is nested, it can have more depth.
In the above example since the status didn't match, it should return false otherwise it should have returned true. how do i compare them. I am new to python. Thanks for your help.

Answer

Note that there were some errors in your dictionary (missing commas).

childDict1 = {
    "assignee": {
        "first":"myFirstName",
        "last":"myLastName"
    },
    "status" : "alive"
}

childDict2 = {
    "assignee": {
        "first":"myFirstName",
        "last":"myLastName"
    },
    "status" : "dead"
}

masterDict = {
    "description": "sample description",
    "assignee": {
        "first":"myFirstName",
        "last":"myLastName"
    },
    "status": "dead",
    "identity": 1234  
}

def contains_subdict(master, child):
    if isinstance(master, dict) and isinstance(child, dict):
        for key in child.keys():
            if key in master:
                if not contains_subdict(master[key], child[key]):
                    return False
        return True
    else:
        if child == master:
            return True
        return False

print contains_subdict(masterDict, childDict1)
print contains_subdict(masterDict, childDict2)

Running the code produces the output:

False
True