How to merge two list of dictionaries based on a value

2024/11/17 4:24:41

I have two lists of dictionaries, lets say:

a = [{'id': 1, 'name': 'a'}]
b = [{'id': 1, 'city': 'b'}]

I want to have a list that merges every dictionary in both lists with the same ID. In this example i expect to have:

a = [{'id': 1, 'name': 'a', 'city': 'b'}]

Is there any cleaner way of doing it other than a for nested into the other?

Thanks

Answer

You can keep track of the ids with another dict (or defaultdict to make things simpler). Then update the items in that dict as you iterate. In the end the dict's values will have your list.

from collections import defaultdict
d = defaultdict(dict)a = [{'id': 1, 'name': 'a'}, {'id': 3, 'name': 'a'}]
b = [{'id': 1, 'city': 'b'}, {'id': 2, 'city': 'c'}, {'id': 3, 'city': 'd'}]for item in a + b:d[item['id']].update(item)
list(d.values())# [{'id': 1, 'name': 'a', 'city': 'b'},
#  {'id': 3, 'name': 'a', 'city': 'd'},
#  {'id': 2, 'city': 'c'}]

Note this will overwrite duplicate values other than id — so if you have two with id: 1 and two different cities, you will only get the last city.

https://en.xdnf.cn/q/71586.html

Related Q&A

How can I format strings to query with mysqldb in Python?

How do I do this correctly:I want to do a query like this:query = """SELECT * FROM sometable order by %s %s limit %s, %s;""" conn = app_globals.pool.connection() cur = con…

Doing many iterations of curve_fit in one go for piecewise function

Im trying to perform what are many iterations of Scipys curve_fit at once in order to avoid loops and therefore increase speed.This is very similar to this problem, which was solved. However, the fact …

python - dictionary iterator for pool map

I am handling set of frozensets. I am trying to find minimal sets for each frozenset in the dictionary output. I have 70k frozensets, so i am making chunk of this frozenset dictionary and parallelizing…

How to get SciPy.integrate.odeint to stop when path is closed?

edit: Its been five years, has SciPy.integrate.odeint learned to stop yet?The script below integrates magnetic field lines around closed paths and stops when it returns to original value within some t…

High-dimensional data structure in Python

What is best way to store and analyze high-dimensional date in python? I like Pandas DataFrame and Panel where I can easily manipulate the axis. Now I have a hyper-cube (dim >=4) of data. I have be…

How to access top five Google result links using Beautifulsoup

I want to access the top five(or any specified number) of links of results from Google. Through research, I found and modified the following code.import requests from bs4 import BeautifulSoup import re…

Logging in a Framework

Imagine there is a framework which provides a method called logutils.set_up() which sets up the logging according to some config.Setting up the logging should be done as early as possible since warning…

Working of the Earth Mover Loss method in Keras and input arguments data types

I have found a code for the Earth Mover Loss in Keras/Tensrflow. I want to compute the loss for the scores given to images but I can not do it until I get to know the working of the Earth Mover Loss gi…

Django Rest Framework writable nested serializer with multiple nested objects

Im trying to create a writable nested serializer. My parent model is Game and the nested models are Measurements. I am trying to post this data to my DRF application using AJAX. However, when try to po…

Django How to Serialize from ManyToManyField and List All

Im developing a mobile application backend with Django 1.9.1 I implemented the follower model and now I want to list all of the followers of a user but Im currently stuck to do that. I also use Django…