Python – Concatenate values with same keys in a list of dictionaries
Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform concatenation of all the key values list that is like in dictionary list. This is quite a common problem and has applications in domains such as day-day programming and web development domain. Let’s discuss the certain ways in which this task can be performed.
Method 1: Using loop
This task can be performed using brute force way. In this we iterate for all the dictionaries and perform the concatenation of like keys by adding one list element to other on the key match.
Python3
# Python3 code to demonstrate working of # Concatenate Similar Key values # Using loop # initializing list test_list = [{ 'gfg' : [ 1 , 5 , 6 , 7 ], 'good' : [ 9 , 6 , 2 , 10 ], 'CS' : [ 4 , 5 , 6 ]}, { 'gfg' : [ 5 , 6 , 7 , 8 ], 'CS' : [ 5 , 7 , 10 ]}, { 'gfg' : [ 7 , 5 ], 'best' : [ 5 , 7 ]}] # printing original list print ( "The original list is : " + str (test_list)) # Concatenate Similar Key values # Using loop res = dict () for dict in test_list: for list in dict : if list in res: res[ list ] + = ( dict [ list ]) else : res[ list ] = dict [ list ] # printing result print ( "The concatenated dictionary : " + str (res)) |
The original list is : [{'gfg': [1, 5, 6, 7], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6]}, {'gfg': [5, 6, 7, 8], 'CS': [5, 7, 10]}, {'gfg': [7, 5], 'best': [5, 7]}] The concatenated dictionary : {'gfg': [1, 5, 6, 7, 5, 6, 7, 8, 7, 5], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6, 5, 7, 10], 'best': [5, 7]}
Method 2: Using defaultdict
Python3
from collections import defaultdict test_list = [{ 'gfg' : [ 1 , 5 , 6 , 7 ], 'good' : [ 9 , 6 , 2 , 10 ], 'CS' : [ 4 , 5 , 6 ]}, { 'gfg' : [ 5 , 6 , 7 , 8 ], 'CS' : [ 5 , 7 , 10 ]}, { 'gfg' : [ 7 , 5 ], 'best' : [ 5 , 7 ]}] print ( "Original List: " + str (test_list)) result = defaultdict( list ) for i in range ( len (test_list)): current = test_list[i] for key, value in current.items(): for j in range ( len (value)): result[key].append(value[j]) print ( "Concatenated Dictionary: " + str ( dict (result))) |
Original List: [{'gfg': [1, 5, 6, 7], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6]}, {'gfg': [5, 6, 7, 8], 'CS': [5, 7, 10]}, {'gfg': [7, 5], 'best': [5, 7]}] Concatenated Dictionary: {'gfg': [1, 5, 6, 7, 5, 6, 7, 8, 7, 5], 'good': [9, 6, 2, 10], 'CS': [4, 5, 6, 5, 7, 10], 'best': [5, 7]}