Python | Merging two list of dictionaries
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.
# Python code to merge two list of dictionaries # based on some value. from collections import defaultdict # List intialization Input1 = [{'roll_no': ['123445', '1212'], 'school_id': 1}, {'roll_no': ['HA-4848231'], 'school_id': 2}] Input2 = [{'roll_no': ['473427'], 'school_id': 2}, {'roll_no': ['092112'], 'school_id': 5}] # Using defaultdic temp = defaultdict(list) # Using extend for elem in Input1: temp[elem['school_id']].extend(elem['roll_no']) for elem in Input2: temp[elem['school_id']].extend(elem['roll_no']) Output = [{"roll_no":y, "school_id":x} for x, y in temp.items()] # printing print(Output) |
[{‘school_id’: 1, ‘roll_no’: [‘123445’, ‘1212’]}, {‘school_id’: 2, ‘roll_no’: [‘HA-4848231’, ‘473427’]}, {‘school_id’: 5, ‘roll_no’: [‘092112’]}]
Method #2: Using extend() only.
# Python code to merge two list of dictionaries # based on some value. # List initialization Input1 = [{'roll_no': ['123445', '1212'], 'school_id': 1}, {'roll_no': ['HA-4848231'], 'school_id': 2}] Input2 = [{'roll_no': ['473427'], 'school_id': 2}, {'roll_no': ['092112'], 'school_id': 5}] # Iterating and using extend to convert for elm2 in Input2: for elm1 in Input1: if elm2['school_id'] == elm1['school_id']: elm1['roll_no'].extend(elm2['roll_no']) break else: Input1.append(elm2) # printing print(Input1) |
[{‘school_id’: 1, ‘roll_no’: [‘123445’, ‘1212’]}, {‘school_id’: 2, ‘roll_no’: [‘HA-4848231’, ‘473427’]}, {‘school_id’: 5, ‘roll_no’: [‘092112’]}]
Recommended Posts:
- Python | Merging two Dictionaries
- Python | Sum list of dictionaries with same key
- Python | Set Difference in list of dictionaries
- Python | Segregating key's value in list of dictionaries
- Python | Get values of particular key in list of dictionaries
- Python | Flatten given list of dictionaries
- Python | Sort given list of dictionaries by date
- Python | Removing dictionary from list of dictionaries
- Python | Split dictionary of lists to list of dictionaries
- Python | Merging duplicates to list of list
- Ways to sort list of dictionaries by values in Python – Using itemgetter
- Ways to sort list of dictionaries by values in Python - Using lambda function
- Get() method for dictionaries in Python
- Python | Subtraction of dictionaries
- Python | Difference in keys of two dictionaries
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



