kevinjaypatel
kevinjaypatel

Reputation: 45

How to search an object list for a specific attribute value that exists in another list of objects

I have two lists

list1 = [obj1, obj2, ... objn] # len(list1) == N
list2 = [obj1, obj2, ... objm] # len(list2) == M

here's a json representation of obj:

obj = {
   "a1": 0,
   "a2": 1,
   "a3": 2
}

How would I determine the objects from list2 with the same value for obj["a1"] as those in list1? Note it's possible to have multiple occurrences of this. The objects in both lists are formatted the same.

I am only interested in seeing if the value for a certain object attribute from one list can be found in another

For example

list1 = [
   {
      "a1":0,
      "a2":5,
      "a3":4
   },
   {
      "a1":2,
      "a2":3,
      "a3":1
   }
   ...
] 

list2 = [
   # first object
   {
      "a1":0,
      "a2":3,
      "a3":1
   },
   # second object
   {
      "a1":3,
      "a2":1,
      "a3":0
   }
   ...
] 

In this case, the first object in list2 contains the same attribute value for obj["a1"] as list1

Upvotes: 0

Views: 65

Answers (4)

MartDogDev
MartDogDev

Reputation: 51

You could try looking into different libraries and you may find an answer. However you can play around with dictionaries to achieve the same results. Let me know if you have any issues with this method.

def get_groups(list1, list2):

    # assuming the obj are dictionaries in lists 1 & 2
    # we store entries into the known_data as 
    # (category, value) : [obj_references]
    # eg known_data = {('a1', 0) : [obj1, obj23, obj3]}

    known_data = {}

    for obj in list1:
        for category, value in obj.items():
            key = (category, value)
            entry = known_data.get(key, []) or []
            entry.append(obj)
            known_data[key] =  entry

    # now we can iterate over list2 and check to see if it shares any keys
    # for groups we store our common key (category, value)
    # and map to a 2D array [ [list1 objs] , [list2 objs]] 
    groups = {}

    for obj in list2:
        for category, value in obj.items():
            key = (category, value)
        
            if key not in known_data:
                continue
        
            entry = groups.get(key) or [[], [known_data[key]]]
            entry[0].append(obj)
            groups[key] = entry
            
    return groups

Upvotes: 0

César Debeunne
César Debeunne

Reputation: 518

The easiest solution would be to simply go through a double loop:

for obj1 in list1:
    for key in obj1:
        for obj2 in list2:
            if (obj1[key] == obj2[key]):
                # Do what you want

Upvotes: 0

spramuditha
spramuditha

Reputation: 355

Check Pandas, you can easily transform the lists to pandas and from there, doing what you need is pretty straight forward.

Index the two pandas with "a1", and then check this link to get intersection

try this; (I have not run the code. but this should work!)

import pandas as pd
df1 = pd.DataFrame(list1)
df2 = pd.DataFrame(list2)

df1.set_index("a1",inplace=True)
df2.set_index("a1",inplace=True)

df1.index.intersection(df2.index) 

This should give you the list of intersections

Upvotes: 1

Deepak Tripathi
Deepak Tripathi

Reputation: 3243

using pandas you can try this

list1 = [
   {
      "a1":0,
      "a2":5,
      "a3":4
   },
   {
      "a1":2,
      "a2":3,
      "a3":1
   }
] 

list2 = [
   # first object
   {
      "a1":0,
      "a2":3,
      "a3":1
   },
   # second object
   {
      "a1":3,
      "a2":1,
      "a3":0
   }
] 

df1 = pd.DataFrame(list1)
df2 = pd.DataFrame(list2)

a1 = df2[df2['a1'].isin(df1['a1'])]
a1.to_json(orient='records', lines=True)

Upvotes: 1

Related Questions