Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Merge two lists of dictionaries

Tags:

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?

like image 506
xiaohan2012 Avatar asked Oct 24 '13 09:10

xiaohan2012


People also ask

Can we merge two dictionaries in Python?

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.

How do you merge two lists in Python?

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.


Video Answer


1 Answers

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.

like image 193
georg Avatar answered Oct 12 '22 14:10

georg