1

I'm hitting two different tables that each return an object of trips, and my goal is to see which trips overlap in each response object. Each object has a key/value of Origin (id of location) and Destination (id of location). How do I iterate through both objects to create a new object that only returns the trips with matching origin and destination key-value pairs?

Example: response_one =

[{'DestinationID': 'a','OriginID': 'b'},
 {'DestinationID': 'c','OriginID': 'd'},
 {'DestinationID': 'c','OriginID': 'a'}]

response_two =

[{'DestinationID': 'd','OriginID': 'b'},
 {'DestinationID': 'e','OriginID': 'd'},
 {'DestinationID': 'c','OriginID': 'a'}]

In this case, DestinationID: "c" and OriginID: "a" are the only ones that are present in both. So How would I go about getting finding which Origin AND Destination ID match in both objects?

JE_2123A
  • 25
  • 5
  • What did you try so far? – Yuri Ginsburg Jun 28 '21 at 23:50
  • Actually it is a task of getting a list of values included in two given lists. Here is a [simple solution](https://stackoverflow.com/a/3834580/6682517) from an old answer. It is not the highest rated answer but it works with lists of dictionaries instead of set-based solutions. – Sergey Shubin Jun 29 '21 at 08:05

1 Answers1

0

Probably not the best way to do it, but for this I would dump the key/value pairs into lists and then use 'set' to detect matches in the two responses.

responses = [response_one, response_two]
response_one_list = []
response_two_list = []
# Create two lists containing lists with the key/value pairs
for index, response in enumerate(responses):
   for response_dict in response:
       for key in response_dict.keys():
          value = response_dict[key]
          if index == 0:
             response_one_list.append([key, value])
          else:
             response_two_list.append([key, value])

# Clean the lists up into hashable tuples
response_one_list = sorted(set(map(tuple, response_one_list)), reverse=True)
response_two_list = sorted(set(map(tuple, response_two_list)), reverse=True)

# Now that we have our two lists of responses, set will show repeats
repeats = set(response_one_list) - set(response_two_list)
print(repeats)
aebange
  • 35
  • 5