Python – Merge Dictionaries List with duplicate Keys

PythonServer Side ProgrammingProgramming

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.

raja
Published on 20-Sep-2021 07:56:21
Advertisements