Getting the difference between 2 lists that contain dictionaries

  • A+
list1 = [{'key1': 'item1'}, {'key2': 'item2'}] list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}] 

Is there a way to get the difference between those two lists?

Basically, I need a scaleable way to get the differences between 2 lists that contain dictionaries. So I'm trying to compare those lists, and just get a return of {'key3': 'item3'}


You could use a list comprehension:

list1 = [{'key1': 'item1'}, {'key2': 'item2'}] list2 = [{'key1': 'item1'}, {'key2': 'item2'}, {'key3': 'item3'}]  print([x for x in list2 if x not in list1]) 

Which will give [{'key3': 'item3'}]


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: