pythondictionary

How to check if one dictionary containing list is a subset of another dictionary with list in python


Hi I have two dictionaries defined which contains lists

dict_1 = {'V1': ['2024-11-07', '2024-11-08'], 'V2': ['2024-11-07', '2024-11-08']}
dict_2 = {'V1': ['2024-11-08'], 'V2': ['2024-11-07']}

both items (key and val) from dict_2 above are subset of dict_1 so I wanted return true in both cases.

I tried to use res = set(dict_2.items()).issubset(set(dict_1.items())) However it works if its simple dictionary like

dict_1 = {'abc' : 1, 'pqr' : 2} 
dict_2 = {'abc' : 1} 

in my case is there any way this can be done?


Solution

  • You can check for each key of dict_2 that its sublist is a subset of the corresponding sublist of dict_1:

    def dict_issubset(maybe_subset, maybe_superset):
        return {
            key: set(sublist).issubset(maybe_superset[key])
            for key, sublist in maybe_subset.items()
        }
    

    so that:

    dict_1 = {'V1': ['2024-11-07', '2024-11-08'], 'V2': ['2024-11-07', '2024-11-08']}
    dict_2 = {'V1': ['2024-11-08'], 'V2': ['2024-11-07']}
    print(dict_issubset(dict_2, dict_1))
    

    outputs:

    {'V1': True, 'V2': True}
    

    Demo: https://ideone.com/wuvTET