Nat
Nat

Reputation: 1762

Best way to compare two arrays with JSON objects as items in python

You have two arrays (dummy values) with JSON objects as each item inside the arrays:

ArrayOne:

[{'keyboards': '1'}, {'keyboards': '2'}, {'keyboards': '3'}, {'mice': '1'}]

ArrayTwo:

[{'keyboards': '1'}, {'keyboards': '2'}, {'mice': '1'}]

I want to loop through each array simultaneously and IF a value in arrayOne exists in arrayTwo but doesnt in arrayTwo, then flag it up (do something).

This is my code example:

for deviceAndID in ArrayOne:
        if deviceAndID in ArrayTwo:
             print("It exists in both arrays")
        else:
             print("Device " + str(deviceAndID) + "is not in arrayTwo")

With this code example it prints out (an example) Device {'keyboard': '1'} is not in arrayTwo for every value in the largest array.

Really I need it to print out the following based on the two arrays above:

It exists in both arrays
It exists in both arrays
Device {'keyboard': '3'} is not in arrayTwo
It exists in both arrays

I have a feeling the issue is caused by the fact each element or item is a json object, so how would I go about this considering they're JSON objects inside the list?

Upvotes: 0

Views: 1760

Answers (1)

Amir Afianian
Amir Afianian

Reputation: 2795

This is what I got based on your question:

>>> ArrayOne = [{'keyboards': '1'}, {'keyboards': '2'}, {'keyboards': '3'}, {'mice': '1'}]
>>> ArrayTwo = [{'keyboards': '1'}, {'keyboards': '2'}, {'mice': '1'}]
>>> for deviceAndID in ArrayOne:
        if deviceAndID in ArrayTwo:
             print("It exists in both arrays")
        else:
             print("Device " + str(deviceAndID) + "is not in arrayTwo")

             
It exists in both arrays
It exists in both arrays
Device {'keyboards': '3'}is not in arrayTwo
It exists in both arrays

Upvotes: 3

Related Questions