Match set of dictionaries. Most elegant solution. Python

2024/9/22 18:28:05

Given two lists of dictionaries, new one and old one. Dictionaries represent the same objects in both lists.
I need to find differences and produce new list of dictionaries where will be objects from new dictionaries only and updated attributes from old dictionaries.
Example:

   list_new=[{ 'id':1,'name':'bob','desc': 'cool guy'},{ 'id':2,'name':'Bill','desc': 'bad guy'},{ 'id':3,'name':'Vasya','desc': None},]list_old=[{ 'id':1,'name':'boby','desc': 'cool guy','some_data' : '12345'},{ 'id':2,'name':'Bill','desc': 'cool guy','some_data' : '12345'},{ 'id':3,'name':'vasya','desc': 'the man','some_data' : '12345'},{ 'id':4,'name':'Elvis','desc': 'singer','some_data' : '12345'},]

In that example I want produce new list where will be only new guys from list_new with updated data. Matched by id. So Bob will become Boby, Bill will become coll guy, Vasya become - the man. End Elvis have to be absent.

Give me an elegant solution. With less amount of iteration loops.

There is way, I resolve that. 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 why I'm doubt, because there is loop inside loop. If there will be lists of 2000 items the process would take same time.

Answer

Can't quite get it to one line, but here's a simpler version:

def match_new(new_list, old_list) :ids = dict((item['id'], item) for item in new_list)return [ids[item['id']] for item in old_list if item['id'] in ids]
https://en.xdnf.cn/q/71918.html

Related Q&A

Cookies using Python and Google App Engine

Im developing an app on the Google App Engine and have run into a problem. I want to add a cookie to each user session so that I will be able to differentiate amongst the current users. I want them all…

Matplotlib animations - how to export them to a format to use in a presentation?

So, I learned how to make cute little animations in matplotlib. For example, this:import numpy as np import matplotlib import matplotlib.pyplot as pltplt.ion()fig = plt.figure() ax = fig.add_subplot(…

Where is python interpreter located in virtualenv?

Where is python intrepreter located in virtual environment ? I am making a GUI project and I stuck while finding the python interpreter in my virtual environment.

Tkinter check which Entry last had focus

I am working on a program that has a virtual keyboard I created using Tkinter. The pages that have the keyboard enabled have entry widgets where the users need to input data. I am using pyautogui as …

Python Popen grep

Id like Popen to execute:grep -i --line-buffered "grave" data/*.txtWhen run from the shell, this gives me the wanted result. If I start, in the very same directory where I test grep, a python…

Url structure and form posts with Flask

In Flask you write the route above the method declaration like so: @app.route(/search/<location>/) def search():return render_template(search.html)However in HTML the form will post to the url in…

How can I simulate a key press in a Python subprocess?

The scenario is, I have a Python script which part of it is to execute an external program using the code below:subprocess.run(["someExternalProgram", "some options"], shell=True)An…

Difference between pd.merge() and dataframe.merge()

Im wondering what the difference is when you merge by pd.merge versus dataframe.merge(), examples below:pd.merge(dataframe1, dataframe2)anddataframe1.merge(dataframe2)

ctypes in python crashes with memset

I am trying to erase password string from memory like it is suggested in here.I wrote that little snippet:import ctypes, sysdef zerome(string):location = id(string) + 20size = sys.getsizeof(string)…

Python __del__ does not work as destructor? [duplicate]

This question already has answers here:What is the __del__ method and how do I call it?(5 answers)Closed 4 years ago.After checking numerous times, I did find inconsistent info about the topic.In some…