Given n
lists with m
dictionaries as their elements, I would like to produce a new list, with a joined set of dictionaries. Each dictionary is guaranteed to have a key called "index", but could have an arbitrary set of keys beyond that. The non-index keys will never overlap across lists. For example, imagine the following two lists:
l1 = [{"index":1, "b":2}, {"index":2, "b":3}, {"index":3, "green":"eggs"}] l2 = [{"index":1, "c":4}, {"index":2, "c":5}]
("b"
would never appear in l2
, since it appeared in l1
, and similarly, "c"
would never appear in l1
, since it appeared in l2
)
I would like to produce a joined list:
l3 = [{"index":1, "b":2, "c":4}, {"index":2, "b":3, "c":5}, {"index":3, "green":"eggs"}]
What is the most efficient way to do this in Python?
To merge multiple dictionaries, the most Pythonic way is to use dictionary comprehension {k:v for x in l for k,v in x. items()} to first iterate over all dictionaries in the list l and then iterate over all (key, value) pairs in each dictionary.
In python, we can use the + operator to merge the contents of two lists into a new list. For example, We can use + operator to merge two lists i.e. It returned a new concatenated lists, which contains the contents of both list_1 and list_2.
However, in case of the same keys in two dictionaries, this method will return the value of the first dictionary, unlike the other methods which return the value from the second dictionary. We can merge the dictionaries by unpacking the second dictionary.
For this article, let us create two dictionaries d1 and d2 which we want to concatenate into a single dictionary: You can merge tw o dictionaries by iterating over the key-value pairs of the second dictionary with the first one.
Given two list of dictionaries, the task is to merge these two lists of dictionaries based on some value. Method #1: Using defaultdict and extend to merge two list of dictionaries based on school_id.
Each dictionary is guaranteed to have a key called "index", but could have an arbitrary set of keys beyond that. The non-index keys will never overlap across lists.
from collections import defaultdict l1 = [{"index":1, "b":2}, {"index":2, "b":3}, {"index":3, "green":"eggs"}] l2 = [{"index":1, "c":4}, {"index":2, "c":5}] d = defaultdict(dict) for l in (l1, l2): for elem in l: d[elem['index']].update(elem) l3 = d.values() # l3 is now: [{'b': 2, 'c': 4, 'index': 1}, {'b': 3, 'c': 5, 'index': 2}, {'green': 'eggs', 'index': 3}]
EDIT: Since l3
is not guaranteed to be sorted (.values()
returns items in no specific order), you can do as @user560833 suggests:
from operator import itemgetter ... l3 = sorted(d.values(), key=itemgetter("index"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With