I have a list of dictionaries A and B. I would like to see for each dictionary in A, specifically the combination of A['serial_number'] and A['date_out'] exists at all in dictionary B. For the examples below case 1 would be TRUE since the combination of 'AAA' and '2022-3-26' exist in a dictionary in B. Case 2 would be FALSE, even though 'BBB' does exist in a dictionary from B, the combination of 'BBB' and '2022-3-27' does not exists. They both exist separately but not when put together.
Is there an efficient way to search the below for each combination from A to see if it exists in B? If it does not exist I would like to return the serial number and date_out.
List A = [{'serial_number': 'AAA', 'cycle_number': 1, 'date_out': '2022-3-26'},
{'serial_number': 'BBB', 'cycle_number': 2, 'date_out': '2022-3-27'},
{'serial_number': 'CCC', 'cycle_number': 3, 'date_out': '2022-3-28'},
{'serial_number': 'AAA', 'cycle_number': 3, 'date_out': '2022-3-29'},
{'serial_number': 'BBB', 'cycle_number': 3, 'date_out': '2022-3-29'}]
List B = [{'serial_number': 'AAA', 'cycle_number': 1, 'date_out': '2022-3-19'},
{'serial_number': 'BBB', 'cycle_number': 2, 'date_out': '2022-3-20'},
{'serial_number': 'CCC', 'cycle_number': 3, 'date_out': '2022-3-27'},
{'serial_number': 'AAA', 'cycle_number': 3, 'date_out': '2022-3-26'},
{'serial_number': 'BBB', 'cycle_number': 3, 'date_out': '2022-3-23'}]
CodePudding user response:
A = [
{'serial_number': 'AAA', 'cycle_number': 1, 'date_out': '2022-3-26'},
{'serial_number': 'BBB', 'cycle_number': 2, 'date_out': '2022-3-27'},
{'serial_number': 'CCC', 'cycle_number': 3, 'date_out': '2022-3-28'},
{'serial_number': 'AAA', 'cycle_number': 3, 'date_out': '2022-3-29'},
{'serial_number': 'BBB', 'cycle_number': 3, 'date_out': '2022-3-29'}
]
B = [
{'serial_number': 'AAA', 'cycle_number': 1, 'date_out': '2022-3-19'},
{'serial_number': 'BBB', 'cycle_number': 2, 'date_out': '2022-3-20'},
{'serial_number': 'CCC', 'cycle_number': 3, 'date_out': '2022-3-27'},
{'serial_number': 'AAA', 'cycle_number': 3, 'date_out': '2022-3-26'},
{'serial_number': 'BBB', 'cycle_number': 3, 'date_out': '2022-3-23'}
]
print(
{ (x['serial_number'], x['date_out']) for x in A }.intersection(
{ (x['serial_number'], x['date_out']) for x in B })
)
Output is a set of tuples containing the values in common:
{('AAA', '2022-3-26')}
CodePudding user response:
First, create a set
of tuples with B['serial_number']
and B['date_out']
. Then, create similar tuple for each element of A
and lookup to see if it exists in the set
.
b = set([(x["serial_number"], x["date_out"]) for x in B])
[(x["serial_number"], x["date_out"]) in b for x in A]
# [True, False, False, False, False]
Also check,
b = set([(x["serial_number"], x["date_out"]) for x in B])
a = set([(x["serial_number"], x["date_out"]) for x in A])
b - a
a - b
a.intersection(b)