Home > Software engineering >  compare structure and key names of two dictionaries, not values
compare structure and key names of two dictionaries, not values

Time:10-11

Let's say I have two dictionaries like this:

dict_1 = {
    "key_1": {
        "key_1_1": "test",
        "key_1_2": "test",
        "key_1_3": "test",
        "key_1_4": [
            {
                "key": "test",
                "value": "test_value"
            },
            {
                "key": "test",
                "value": "test_value"
            }
        ]
    }
}

dict_2 = {
    "key_1": {
        "key_1_1": "test1",
        "key_1_2": "test1",
        "key_1_3": "test1",
        "key_1_4": [
            {
                "key": "test1",
                "value": "test_value1"
            },
            {
                "key": "test1",
                "value": "test_value1"
            }
        ]
    }
}

Is there a way that I can compare these two dictionaries and return either True or False. I have tried:

dict_1 == dict2

and also deepdiff but it is returning differences in values. In my case, dictionary structure are the same, also key names are the same and it should return me True. I don't care about the values

CodePudding user response:

You could create a function that replaces all scalar values in your object with a dummy value, such as None.

dict_1 = {
    "key_1": {
        "key_1_1": "test",
        "key_1_2": "test",
        "key_1_3": "test",
        "key_1_4": [
            {
                "key": "test",
                "value": "test_value"
            },
            {
                "key": "test",
                "value": "test_value"
            }
        ]
    }
}

dict_2 = {
    "key_1": {
        "key_1_1": "test1",
        "key_1_2": "test1",
        "key_1_3": "test1",
        "key_1_4": [
            {
                "key": "test1",
                "value": "test_value1"
            },
            {
                "key": "test1",
                "value": "test_value1"
            }
        ]
    }
}

def just_keys(obj):
    if isinstance(obj, dict):
        return {k: just_keys(v) for k,v in obj.items()}
    elif isinstance(obj, list):
        return [just_keys(item) for item in obj]
    else:
        return None

def keys_equal(a,b):
    return just_keys(a) == just_keys(b)


print(just_keys(dict_1))
print(just_keys(dict_2))
print(keys_equal(dict_1, dict_2))

Result:

{'key_1': {'key_1_1': None, 'key_1_2': None, 'key_1_3': None, 'key_1_4': [{'key': None, 'value': None}, {'key': None, 'value': None}]}}
{'key_1': {'key_1_1': None, 'key_1_2': None, 'key_1_3': None, 'key_1_4': [{'key': None, 'value': None}, {'key': None, 'value': None}]}}
True
  • Related