Given two lists of dictionaries:
>>> lst1 = [{id: 1, x: "one"},{id: 2, x: "two"}] >>> lst2 = [{id: 2, x: "two"}, {id: 3, x: "three"}] >>> merge_lists_of_dicts(lst1, lst2) #merge two lists of dictionary items by the "id" key [{id: 1, x: "one"}, {id: 2, x: "two"}, {id: 3, x: "three"}]
Any way to implement merge_lists_of_dicts
what merges two lists of dictionary based on the dictionary items' keys?
Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.
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.
Perhaps the simplest option
result = {x['id']:x for x in lst1 + lst2}.values()
This keeps only unique ids
in the list, not preserving the order though.
If the lists are really big, a more realistic solution would be to sort them by id
and merge iteratively.
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