Skip to content
Related Articles

Related Articles

Improve Article
Python – Concatenate values with same keys in a list of dictionaries
  • Last Updated : 08 May, 2020

Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform concatenation of all the keys values list that are like in dictionary list. This is quite common problem and has application in domains such as day-day programming and web development domain. Lets discuss certain way in which this task can be performed.

Method : 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 elements to other on the key match.




# 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)) 
Output :
The original list is : [{'CS': [4, 5, 6], 'good': [9, 6, 2, 10], 'gfg': [1, 5, 6, 7]}, {'CS': [5, 7, 10], 'gfg': [5, 6, 7, 8]}, {'best': [5, 7], 'gfg': [7, 5]}]
The concatenated dictionary : {'gfg': [1, 5, 6, 7, 5, 6, 7, 8, 7, 5], 'good': [9, 6, 2, 10], 'best': [5, 7], 'CS': [4, 5, 6, 5, 7, 10]}

 

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course




My Personal Notes arrow_drop_up
Recommended Articles
Page :