-4

Inputs:

list1 = [{'item_type':1,'value':55, 'title':'abc'},{'item_type':2,'value':43, 'title':'def'},{'item_type':3,'value':35, 'title':'ghi'}]

list2 = [{'item_type':2,'value':13, 'title':'jkl'},{'item_type':3,'value':85, 'title':'mno'}]

Challange1: If the item_type is present in list2 then that should take the priority.

expected result:

final_result = [{'item_type':1,'value':55, 'title':'abc'},{'item_type':2,'value':13, 'title':'jkl'},{'item_type':3,'value':85, 'title':'mno'}]

Challange2: It should merge list1 and list2 based on unique item_type and keep the higher 'value' dictionary.

expected result:

final_result = [{'item_type':1,'value':55, 'title':'abc'},{'item_type':2,'value':43, 'title':'def'},{'item_type':3,'value':85, 'title':'mno'}]

I have solved both the challenges,but I want to optimize this code using list comprehensive, lambda function. please help me.

this is my code

Challange1:

final_result = []
list1 = [{'item_type':1,'value':55, 'title':'abc'},{'item_type':2,'value':43, 'title':'def'},{'item_type':3,'value':35, 'title':'ghi'}]
list2 = [{'item_type':2,'value':13, 'title':'jkl'},{'item_type':3,'value':85, 'title':'mno'}]

for i in range(len(list1)):
    for j in range(len(list2)):
        if list1[i]['item_type'] == list2[j]['item_type']:
            if list1[i]['item_type'] < list2[j]['item_type']:
                final_result.append(list1[i])
            else:
                final_result.append(list2[j])
            break
    else:
        final_result.append(list1[i])
print(final_result)

Challange2:

final_result = []
list1 = [{'item_type':1,'value':55, 'title':'abc'},{'item_type':2,'value':43, 'title':'def'},{'item_type':3,'value':35, 'title':'ghi'}]
list2 = [{'item_type':2,'value':13, 'title':'jkl'},{'item_type':3,'value':85, 'title':'mno'}]

for i in range(len(list1)):
    for j in range(len(list2)):
        if list1[i]['item_type'] == list2[j]['item_type']:
            if list1[i]['value'] > list2[j]['value']:
                final_result.append(list1[i])
            else:
                final_result.append(list2[j])
            break
    else:
        final_result.append(list1[i])
print(final_result)

2 Answers2

1

copy.deepcopy() if you want a deep copy. But you can also make a shallow copy with copy.copy() or newdict=dict(olddict) or olddict.copy().

Joshua Fox
  • 18,704
  • 23
  • 87
  • 147
0

You can use copy method.

dict_1 = { "a" : {"b": "c"}}
dict_2 = dict_1.copy()
Astik Gabani
  • 599
  • 1
  • 4
  • 11