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 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.

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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)) 

chevron_right


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.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

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.


Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.