Search code examples
pythondictionaryintersection

TypeError: unhashable type: 'list' when finding intersection of two dictionaries with values that are lists


I have dictionary a and b. a looks like this:

{
'q1': ['d5', 'd6', 'd90', 'd91', 'd119', 'd144', 'd181', 'd399'],
 'q2': ['d236', 'd166'],
 'q3': ['d552', 'd401', 'd1297', 'd1296'],
 'q4': ['d99', 'd115', 'd257', 'd258'],
 'q5': ['d20', 'd56', 'd57', 'd58', 'd19']
}

and b looks like

{
'q1': ['d707',
  'd144',
  'd542',
  'd329',
  'd395',
  'd730',
  'd158',
  'd77',
  'd486',
  'd623'],
 'q2': ['d189',
  'd575',
  'd179',
  'd1182',
  'd160',
  'd188',
  'd660',
  'd1061',
  'd173',
  'd185'],
 'q3': ['d730',
  'd329',
  'd1066',
  'd14',
  'd163',
  'd401',
  'd753',
  'd44',
  'd92',
  'd368'],
 'q4': ['d798',
  'd97',
  'd99',
  'd927',
  'd1195',
  'd131',
  'd257',
  'd315',
  'd151',
  'd193'],
 'q5': ['d189',
  'd1347',
  'd423',
  'd1040',
  'd174',
  'd1231',
  'd197',
  'd721',
  'd1307',
  'd1352']
}

I'd like to find the overlap of the two, as in where I would find matching value elements for each shared key between the dictionaries I tried dict(ret_docs.items() & reljudges.items()) but that returned the error in the title.


Solution

  • {key: [item for item in items if item in second.get(key, [])]
        for key, items in first.items() if key in second}