Given two lists of dictionaries, new and old. Dictionaries represent the same objects in both lists. I need to find the differences and create a new list of dictionaries, where there will be objects only from new dictionaries and updated attributes from old dictionaries.
Example:
list_new=[ { 'id':1, 'name':'bob', 'desc': 'cool gay' }, { 'id':2, 'name':'Bill', 'desc': 'bad gay' }, { 'id':3, 'name':'Vasya', 'desc': None }, ] list_old=[ { 'id':1, 'name':'boby', 'desc': 'cool gay', 'some_data' : '12345' }, { 'id':2, 'name':'Bill', 'desc': 'cool gay', 'some_data' : '12345' }, { 'id':3, 'name':'vasya', 'desc': 'the man', 'some_data' : '12345' }, { 'id':4, 'name':'Elvis', 'desc': 'singer', 'some_data' : '12345' }, ]
So .. In this example, I want to create a new list, where there will be only new gays from list_new with updated data. Corresponds to id . So, Bob will become Bobi, Bill will become burned, Vasya will become - a man. The end of Elvis must be absent.
Give me an elegant solution. With fewer iteration cycles.
There is a way, I allow it. Which is not the best:
def match_dict(new_list, old_list) ids_new=[] for item in new_list: ids_new.append(item['id']) result=[] for item_old in old_medias: if item_old['id'] in ids_new: for item_new in new_list: if item_new['id']=item_old['id'] item_new['some_data']=item_old['some_data'] result.append(item_new) return result
The reason I doubt it is because there is a cycle inside the loop. If there are lists of 2000 items, the process will take the same time.