简体   繁体   中英

Merging two lists of dictionaries using common id key

I have the following two lists of dictionaries:

list_1 = [
   {'id': '1', 'name': 'Johnny Johson1'},
   {'id': '2', 'name': 'Johnny Johson2'},
   {'id': '1', 'name': 'Johnny Johson1'},
   {'id': '3', 'name': 'Johnny Johson3'},
]
list_2 = [
   {'id': '1', 'datetime': '2020-01-06T12:30:00.000Z'},
   {'id': '2', 'datetime': '2020-01-06T14:00:00.000Z'},
   {'id': '1', 'datetime': '2020-01-06T15:30:00.000Z'},
   {'id': '3', 'datetime': '2020-01-06T15:30:00.000Z'},
]

Essentially, I would like no loss of data even on duplicate IDs, as they represent different events (there is a sepearate ID for that, but for the purpose of demonstrating the problem, is not needed). If there are any IDs in one list, not in the other, then disregard that ID all together.

Ideally, I would like to end up with the following (from the amalgamation of the two lists):

list_3 = [
   {'id': '1', 'name': 'Johnny Johson1', 'datetime': '2020-01-06T12:30:00.000Z'},
   {'id': '2', 'name': 'Johnny Johson2', 'datetime': '2020-01-06T14:00:00.000Z'},
   {'id': '1', 'name': 'Johnny Johson1', 'datetime': '2020-01-06T15:30:00.000Z'},
   {'id': '3', 'name': 'Johnny Johson3', 'datetime': '2020-01-06T15:30:00.000Z'},
]

You can use the following list comprehension, which uses the double asterisk keyword argent unpacking syntax, evaluated on both lists using pairwise elements obtained with zip(). This has the effect of combining the two dictionaries into one.

list_3 = [{**x, **y} for x, y in zip(list_1, list_2)]

Output:

>>> list3
[{'id': '1', 'name': 'Johnny Johson1', 'datetime': '2020-01-06T12:30:00.000Z'},
 {'id': '2', 'name': 'Johnny Johson2', 'datetime': '2020-01-06T14:00:00.000Z'},
 {'id': '1', 'name': 'Johnny Johson1', 'datetime': '2020-01-06T15:30:00.000Z'},
 {'id': '3', 'name': 'Johnny Johson3', 'datetime': '2020-01-06T15:30:00.000Z'}]

Note that this approach requires at least Python 3.5.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM