
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python – Merge Dictionaries List with duplicate Keys
When it is required to merge dictionaries list with duplicate keys, the keys of the strings are iterated over and depending on the condition, the result is determined.
Example
Below is a demonstration of the same
my_list_1 = [{"aba": 1, "best": 4}, {"python": 10, "fun": 15}, {"scala": "fun"}] my_list_2 = [{"scala": 6}, {"python": 3, "best": 10}, {"java": 1}] print("The first list is : ") print(my_list_1) print("The second list is : ") print(my_list_2) for i in range(0, len(my_list_1)): id_keys = list(my_list_1[i].keys()) for key in my_list_2[i]: if key not in id_keys: my_list_1[i][key] = my_list_2[i][key] print("The result is : " ) print(my_list_1)
Output
The first list is : [{'aba': 1, 'best': 4}, {'python': 10, 'fun': 15}, {'scala': 'fun'}] The second list is : [{'scala': 6}, {'python': 3, 'best': 10}, {'java': 1}] The result is : [{'aba': 1, 'best': 4, 'scala': 6}, {'python': 10, 'fun': 15, 'best': 10}, {'scala': 'fun', 'java': 1}]
Explanation
Two list of dictionaries are defined and displayed on the console.
The list of dictionary is iterated over and the keys are accessed.
These keys are stored in a variable.
The second list of dictionary is iterated over, and if the keys in this are not present in the previous variable, the specific keys from both the lists are equated.
The result is displayed on the console.
- Related Articles
- Handling missing keys in Python dictionaries
- Python - Intersect two dictionaries through keys
- How to merge multiple Python dictionaries?
- Python program to merge to dictionaries.
- Python program to merge two Dictionaries
- Python Program to get all unique keys from a List of Dictionaries
- Python - Difference in keys of two dictionaries
- How to create Python dictionary with duplicate keys?
- How can we merge two Python dictionaries?
- Find keys with duplicate values in dictionary in Python
- How to merge two Python dictionaries in a single expression?
- C# program to merge two Dictionaries
- How to find difference in keys contained in two Python dictionaries?
- Flatten given list of dictionaries in Python
- Python – Remove Dictionaries with Matching Values

Advertisements