Search code examples
pythonlistdictionarydifference

Compare dictionary list values to the list of list values using python


I have a dictionary values and list of list values. I need to compare the list values with the dictionary values and get the matched data with key and value pairs.

My dictionary:

res = {
    'cXboTHyIeZaof6x7': ['#de6262', '#ffb88c'],
    '19hyHnlzDMEDJ9N5': ['#ffcc66', '#FFFFFF'],
    'TByXB1YzYSJW2kXO': ['#7A7FBC', '#807CC4'],
    'utTtWdchE2T6vUF5': ['#A3DAC3', '#8BD0D4']
}

My list of list values:

diff_tolistoflist = [
    ['#de6262', '#ffb88c'],
    ['#A3DAC3', '#8BD0D4']
]

Expected output:

test = {
    'cXboTHyIeZaof6x7': ['#de6262', '#ffb88c'],
    'utTtWdchE2T6vUF5': ['#A3DAC3', '#8BD0D4']
}

I need to compare dict values and list of values to get the similar data with key and value pair.


Solution

  • You can use a dictionary comprehension which is quite easy to read:

    d = {k:v for k,v in res.items() if v in diff_tolistoflist}
    print(d)  
    # {'cXboTHyIeZaof6x7': ['#de6262', '#ffb88c'], 'utTtWdchE2T6vUF5': ['#A3DAC3', '#8BD0D4']}