natrayanp / stuy

0 stars 0 forks source link

https://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches #1

Open natrayanp opened 6 years ago

natrayanp commented 6 years ago

https://stackoverflow.com/questions/1388818/how-can-i-compare-two-lists-in-python-and-return-matches

Compare 2 arrays:

set(a).intersection(b) set(a).difference(b)

natrayanp commented 6 years ago

Compare 2 JSON array and return non matching with the base:

this can be used to find the difference in the stocklist array and mflist array

predict = {'eggs': [{'name': 2,"address":"pasir 2"},{'name': 2,"address":"pasir 2"}],'ham': [{'name': 1,"address":"pasir 1"},{'name': 2,"address":"pasir 2"},{'name': 3,"address":"pasir 3"}]} actual = {'eggs': [{'name': 2,"address":"pasir 2"}], 'ham': [{'name': 1,"address":"pasir 1"},{'name': 2,"address":"pasir 2"}]} difference = {} for key, value in predict.items(): difference[key] = [el for el in predict[key] if (key not in actual) or (el not in actual[key])] print(difference)

natrayanp commented 6 years ago

To check if the 2 JSON are equal or not:

a = json.loads(""" { "errors": [ {"error": "invalid", "field": "email"}, {"error": "required", "field": "name"} ], "success": false } """)

b = json.loads(""" { "success": false, "errors": [ {"error": "required", "field": "name"}, {"error": "invalid", "field": "email"} ] } """)

def ordered(obj): if isinstance(obj, dict): return sorted((k, ordered(v)) for k, v in obj.items()) if isinstance(obj, list): return sorted(ordered(x) for x in obj) else: return obj If we apply this function to a and b, the results compare equal:

ordered(a) == ordered(b)