Comparing lists with objects

Let's say I have 2 lists

list1 = []
list2 = []

and a dictionary

dict = {'SNo': 1, 'Data': "Random Data"}

Let the list1, list2 contain multiple instances of this dictionary with different SNo and data. Some of the SNo may be same. But the Data need not be.

I want to merge (and sort) these 2 lists based on the SNo , maintaining their structure while ignoring the ones with the same SNo.

Assumption: If the list of dictionaries have the same SNo, then list2's entry is ignored.

Upvotes: 0

Views: 232

Answers (2)

Sriram
Sriram

Reputation: 1728

Here is the sorted builtin func to do that,

    sorted(list1+list2, key=lambda x: x['SNo'])

Each item is sorted based on the value returned from the lambda function. For each item now the list will sorted based on the value of 'id' in each.You can also sort in reverse order

    sorted(list1+list2, key=lambda x: x['SNo'], reverse=True)

Note: This might not ignore duplicate value of "SNo". You can remove it after obtaining the sorted merged list

Upvotes: 1

Fuji Komalan
Fuji Komalan

Reputation: 2047

list1 = [{'SNo': 1, 'Data': "abc"} , {'SNo': 2, 'Data': "bcd"}, {'SNo': 2, 'Data': "def"}]
list2 = [{'SNo': 3, 'Data': "abc"} , {'SNo': 4, 'Data': "bcd"}, {'SNo': 3, 'Data': "def"}]

# to keep merged lists
final_list = []

# this list will track if sno exit alreay
sno_list = []

# take evry dict from combined list:
for d in list1+list2:
  # extract sno 
  sno = d['SNo']
  # if sno not present in sno_list add that sno.
  if sno not in sno_list:
    # add evry dict , if its sno not present in the sno_list.
    final_list.append(d)
    sno_list.append(sno)

print(final_list)    

#[{'SNo': 1, 'Data': 'abc'}, {'SNo': 2, 'Data': 'bcd'}, {'SNo': 3, 'Data': 'abc'}, {'SNo': 4, 'Data': 'bcd'}]

#sorting list

result = sorted(final_list,key=lambda d:d['SNo'])
#[{'SNo': 1, 'Data': 'abc'}, {'SNo': 2, 'Data': 'bcd'}, {'SNo': 3, 'Data': 'abc'}, {'SNo': 4, 'Data': 'bcd'}]
print(result)

Upvotes: 1

Related Questions