Python - Concatenate String values in Dictionary List
Last Updated :
25 Apr, 2023
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))
OutputThe 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:
- Import defaultdict from the collections module.
- 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.
- Loop through each dictionary in the list and use the id value as the key for the defaultdict.
- Concatenate the value of the gfg key in the current dictionary with the value of the same key in the defaultdict using join() method.
- Append the current dictionary to the defaultdict.
- Convert the defaultdict to a list of dictionaries.
- 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))
OutputThe 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.
Similar Reads
Python - Concatenate Dictionary string values The task of concatenating string values in a Python dictionary involves combining the values associated with the same key across multiple dictionaries. This operation allows us to merge string data in an efficient manner, especially when dealing with large datasets .For example, given two dictionari
4 min read
Python | Concatenate dictionary value lists Sometimes, while working with dictionaries, we might have a problem in which we have lists as it's value and wish to have it cumulatively in single list by concatenation. This problem can occur in web development domain. Let's discuss certain ways in which this task can be performed. Method #1 : Usi
5 min read
Convert Dictionary to String List in Python The task of converting a dictionary to a string list in Python involves transforming the key-value pairs of the dictionary into a formatted string and storing those strings in a list. For example, consider a dictionary d = {1: 'Mercedes', 2: 'Audi', 3: 'Porsche', 4: 'Lambo'}. Converting this to a st
3 min read
Python - Concatenate Ranged Values in String list Given list of strings, perform concatenation of ranged values from the Strings list. Input : test_list = ["abGFGcs", "cdforef", "asalloi"], i, j = 3, 5 Output : FGorll Explanation : All string sliced, FG, or and ll from all three strings and concatenated. Input : test_list = ["aGFGcs", "cforef", "aa
5 min read
Convert List Of Dictionary into String - Python In Python, lists can contain multiple dictionaries, each holding key-value pairs. Sometimes, we need to convert a list of dictionaries into a single string. For example, given a list of dictionaries [{âaâ: 1, âbâ: 2}, {âcâ: 3, âdâ: 4}], we may want to convert it into a string that combines the conte
3 min read
Python Convert Dictionary to List of Values Python has different types of built-in data structures to manage your data. A list is a collection of ordered items, whereas a dictionary is a key-value pair data. Both of them are unique in their own way. In this article, the dictionary is converted into a list of values in Python using various con
3 min read
Convert Dictionary String Values to List of Dictionaries - Python We are given a dictionary where the values are strings containing delimiter-separated values and the task is to split each string into separate values and convert them into a list of dictionaries, with each dictionary containing a key-value pair for each separated value. For example: consider this d
2 min read
Python - Convert key-values list to flat dictionary We are given a list that contains tuples with the pairs of key and values we need to convert that list into a flat dictionary. For example a = [("name", "Ak"), ("age", 25), ("city", "NYC")] is a list we need to convert it to dictionary so that output should be a flat dictionary {'name': 'Ak', 'age':
3 min read
Python - Convert Dictionary to Concatenated String In Python, sometimes we need to convert a dictionary into a concatenated string. The keys and values of the dictionary are combined in a specific format to produce the desired string output. For example, given the dictionary {'a': 1, 'b': 2, 'c': 3}, we may want the string "a:1, b:2, c:3". Let's dis
3 min read
Python - Concatenate Tuple to Dictionary Key Given Tuples, convert them to the dictionary with key being concatenated string. Input : test_list = [(("gfg", "is", "best"), 10), (("gfg", "for", "cs"), 15)] Output : {'gfg is best': 10, 'gfg for cs': 15} Explanation : Tuple strings concatenated as strings. Input : test_list = [(("gfg", "is", "best
6 min read