Open In App

Python – Concatenate String values in Dictionary List

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python records data, we can have a problem in which we require to perform concatenation of string values of keys by matching at particular key like ID. This kind of problem can have application in web development domain. Let’s discuss certain way in which this task can be performed.

Input : test_list = [{‘id’: 17, ‘gfg’: ‘geeksfor’}, {‘id’: 12, ‘gfg’: ‘geeks’}, {‘id’: 34, ‘gfg’: ‘good’}] 
Output : [{‘id’: 17, ‘gfg’: ‘geeksfor’}, {‘id’: 12, ‘gfg’: ‘geeks’}, {‘id’: 34, ‘gfg’: ‘good’}] 

Input : test_list = [{‘id’: 1, ‘gfg’: ‘geeksfor’}, {‘id’: 1, ‘gfg’: ‘geeks’}, {‘id’: 1, ‘gfg’: ‘good’}] 
Output : [{‘id’: 1, ‘gfg’: ‘geeksforgeeksgood’}]

Method #1: Using loop This is one way to solve this problem. In this, we check each key and then perform merge on basis of equality key and perform concatenation of particular required key in brute force approach. 

Python3




# Python3 code to demonstrate working of
# Concatenate String values in Dictionary List
# Using loop
 
# initializing list
test_list = [{'gfg' : "geeksfor", 'id' : 12, 'best' : (1, 2)},
            {'gfg' : "geeks", 'id' : 12, 'best' : (6, 2)},
            {'gfg' : "good", 'id' : 34, 'best' : (7, 2)}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing compare key
comp_key = 'id'
 
# initializing concat key
conc_key = 'gfg'
 
# Concatenate String values in Dictionary List
# Using loop
res = []
for ele in test_list:
    temp = False
    for ele1 in res:
        if ele1[comp_key] == ele[comp_key]:
            ele1[conc_key] = ele1[conc_key] + ele[conc_key]
            temp = True
            break
    if not temp:
        res.append(ele)
 
# printing result
print("The converted Dictionary list : " + str(res))


Output

The original list is : [{'gfg': 'geeksfor', 'id': 12, 'best': (1, 2)}, {'gfg': 'geeks', 'id': 12, 'best': (6, 2)}, {'gfg': 'good', 'id': 34, 'best': (7, 2)}]
The converted Dictionary list : [{'gfg': 'geeksforgeeks', 'id': 12, 'best': (1, 2)}, {'gfg': 'good', 'id': 34, 'best': (7, 2)}]

Time Complexity: O(n*n)
Auxiliary Space: O(n)

Method #2: Using defaultdict and join()

 steps for the approach:

  1. Import defaultdict from the collections module.
  2. Initialize a defaultdict with list as the default value. This will help us to append new dictionaries with the same id value to the same key.
  3. Loop through each dictionary in the list and use the id value as the key for the defaultdict.
  4. Concatenate the value of the gfg key in the current dictionary with the value of the same key in the defaultdict using join() method.
  5. Append the current dictionary to the defaultdict.
  6. Convert the defaultdict to a list of dictionaries.
  7. Print the final list of dictionaries.

Python3




# Python3 code to demonstrate working of
# Concatenate String values in Dictionary List
# Using defaultdict and join()
 
from collections import defaultdict
 
# initializing list
test_list = [{'gfg': "geeksfor", 'id': 12, 'best': (1, 2)},
             {'gfg': "geeks", 'id': 12, 'best': (6, 2)},
             {'gfg': "good", 'id': 34, 'best': (7, 2)}]
 
# printing original list
print("The original list is : " + str(test_list))
 
# initializing compare key
comp_key = 'id'
 
# initializing concat key
conc_key = 'gfg'
 
# Concatenate String values in Dictionary List
# Using defaultdict and join()
d = defaultdict(list)
for ele in test_list:
    d[ele[comp_key]].append(ele)
     
for k, v in d.items():
    d[k] = {conc_key: ''.join([i[conc_key] for i in v])}
 
res = list(d.values())
 
# printing result
print("The converted Dictionary list : " + str(res))


Output

The original list is : [{'gfg': 'geeksfor', 'id': 12, 'best': (1, 2)}, {'gfg': 'geeks', 'id': 12, 'best': (6, 2)}, {'gfg': 'good', 'id': 34, 'best': (7, 2)}]
The converted Dictionary list : [{'gfg': 'geeksforgeeks'}, {'gfg': 'good'}]

Time Complexity: O(N*M), where N is the number of dictionaries in the list and M is the average length of the concatenated strings.
Auxiliary Space: O(N*M), as we are creating a dictionary with the concatenated strings as values.



Last Updated : 25 Apr, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads