I have been trying to play abit with two list that includes dicts. Basically I have two list that are following:

listA = [{'name': 'ColorR', 'color': 'Red'}, {'name': 'ColorB', 'color': 'Blue'}, {'name': 'ColorP', 'color': 'Purple'}, {'name': 'ColorO', 'color': 'Orange'}, {'name': 'ColorW', 'color': 'White'}]
listB = [{'name': 'ColorR', 'color': 'Red'}, {'name': 'ColorP', 'color': 'Purple'}, {'name': 'ColorO', 'color': 'Orange'}, {'name': 'ColorW', 'color': 'White'}]

What I try to achieve here is that I want to compare listA with listB and print out whatever that is not in listB from listA. In our case we don't have {'name': 'ColorB', 'color': 'Blue'}in listB meaning in that case the output would be:

{'name': 'ColorB', 'color': 'Blue'}

However I did not found any similar to my problem due to I have "comma" inside a dict. (maybe it is not a correct of dicts??)

I would appreciate every sort of help to solve my issue of printing out the dicts that are not in listB.

3 Answers

2
Yusufsn On Best Solutions

It's simple. Use loop to iterate each element in listA and if-statement to compare it with all elements in listB:

listA = [{'name': 'ColorR', 'color': 'Red'}, {'name': 'ColorB', 'color': 'Blue'}, {'name': 'ColorP', 'color': 'Purple'}, {'name': 'ColorO', 'color': 'Orange'}, {'name': 'ColorW', 'color': 'White'}]
listB = [{'name': 'ColorR', 'color': 'Red'}, {'name': 'ColorP', 'color': 'Purple'}, {'name': 'ColorO', 'color': 'Orange'}, {'name': 'ColorW', 'color': 'White'}]

for A in listA:
    if A not in listB:
        print(A)

Output:

{'name': 'ColorB', 'color': 'Blue'}
1
Işık Kaplan On
>>> listA = [{'name': 'ColorR', 'color': 'Red'}, {'name': 'ColorB', 'color': 'Blue'}, {'name': 'ColorP', 'color': 'Purple'}, {'name': 'ColorO', 'color': 'Orange'}, {'name': 'ColorW', 'color': 'White'}]
>>> listB = [{'name': 'ColorR', 'color': 'Red'}, {'name': 'ColorP', 'color': 'Purple'}, {'name': 'ColorO', 'color': 'Orange'}, {'name': 'ColorW', 'color': 'White'}]
>>> [item for item in listA if item not in listB]
[{'name': 'ColorB', 'color': 'Blue'}]
>>>
3
Jean-François Fabre On

you can approach this problem with a O(n^2) complexity by using in in a loop (like in this answer), but you can also rebuild listB as a set of tuples to reduce complexity to O(n) (you need to transform dictionaries into tuples so they can be added in a set):

listA = [{'name': 'ColorR', 'color': 'Red'}, {'name': 'ColorB', 'color': 'Blue'}, {'name': 'ColorP', 'color': 'Purple'}, {'name': 'ColorO', 'color': 'Orange'}, {'name': 'ColorW', 'color': 'White'}]
listB = [{'name': 'ColorR', 'color': 'Red'}, {'name': 'ColorP', 'color': 'Purple'}, {'name': 'ColorO', 'color': 'Orange'}, {'name': 'ColorW', 'color': 'White'}]

listB = {tuple(x.items()) for x in listB}

difference = [A for A in listA if tuple(A.items()) not in listB]

result:

>>> difference
[{'color': 'Blue', 'name': 'ColorB'}]

tuple(A.items()) not in listB has to build a tuple each time, but after that not in operation is O(1)