Open In App

Python – Concatenate Dictionary string values

Last Updated : 27 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with dictionaries, we might have utility problem in which we need to perform elementary operation among the common keys of dictionaries. This can be extended to any operation to be performed. Let’s discuss string concatenation of like key values and ways to solve it in this article. 

Method #1 : Using dictionary comprehension + keys() The combination of above two can be used to perform this particular task. This is just a shorthand to the longer method of loops and can be used to perform this task in one line. 

Python3




# Python3 code to demonstrate working of
# Concatenate Dictionary string values
# Using dictionary comprehension + keys()
 
# Initialize dictionaries
test_dict1 = {'gfg' : 'a', 'is' : 'b', 'best' : 'c'}
test_dict2 = {'gfg' : 'd', 'is' : 'e', 'best' : 'f'}
 
# printing original dictionaries
print("The original dictionary 1 : " + str(test_dict1))
print("The original dictionary 2 : " + str(test_dict2))
 
# Using dictionary comprehension + keys()
# Concatenate Dictionary string values
res = {key: test_dict1[key] + test_dict2.get(key, '') for key in test_dict1.keys()}
 
# printing result
print("The string concatenation of dictionary is : " + str(res))


Output : 

The original dictionary 1 : {'gfg': 'a', 'is': 'b', 'best': 'c'}
The original dictionary 2 : {'gfg': 'd', 'is': 'e', 'best': 'f'}
The string concatenation of dictionary is : {'gfg': 'ad', 'is': 'be', 'best': 'cf'}

Time Complexity: O(n*n), where n is the length of the list test_dict
Auxiliary Space: O(n) additional space of size n is created where n is the number of elements in the res list

  Method #2 : Using Counter() + “+” operator The combination of above method can be used to perform this particular task. In this, the Counter function converts the dictionary in the form in which the plus operator can perform the task of concatenation. 

Python3




# Python3 code to demonstrate working of
# Concatenate Dictionary string values
# Using Counter() + "+" operator
from collections import Counter
 
# Initialize dictionaries
test_dict1 = {'gfg' : 'a', 'is' : 'b', 'best' : 'c'}
test_dict2 = {'gfg' : 'd', 'is' : 'e', 'best' : 'f'}
 
# printing original dictionaries
print("The original dictionary 1 : " + str(test_dict1))
print("The original dictionary 2 : " + str(test_dict2))
 
# Using Counter() + "+" operator
# Concatenate Dictionary string values
temp1 = Counter(test_dict1)
temp2 = Counter(test_dict2)
res = Counter({key : temp1[key] + temp2[key] for key in temp1})
 
# printing result
print("The string concatenation of dictionary is : " + str(dict(res)))


Output : 

The original dictionary 1 : {'gfg': 'a', 'is': 'b', 'best': 'c'}
The original dictionary 2 : {'gfg': 'd', 'is': 'e', 'best': 'f'}
The string concatenation of dictionary is : {'gfg': 'ad', 'is': 'be', 'best': 'cf'}

 concatenate dictionary string values:

Approach:

Iterate over each key in dict1.
For each key, get the corresponding value from dict1 and dict2 and concatenate them using the + operator.
Add the key-value pair to the concatenated_dict dictionary.
Return the concatenated_dict dictionary.

Python3




dict1 = {'gfg': 'a', 'is': 'b', 'best': 'c'}
dict2 = {'gfg': 'd', 'is': 'e', 'best': 'f'}
 
concatenated_dict = {key: dict1[key] + dict2[key] for key in dict1}
print(concatenated_dict)


Output

{'gfg': 'ad', 'is': 'be', 'best': 'cf'}

Time complexity: The time complexity of this approach is O(n)

Space complexity: The space complexity of this approach is O(n)

Method 4: Using a loop and the .update() method

  • Initialize two dictionaries test_dict1 and test_dict2 with some key-value pairs.
  • Print the original dictionaries using the print() function.
  • Use dictionary comprehension along with the keys() method to concatenate the string values of the two dictionaries.
  • The dictionary comprehension creates a new dictionary res with the same keys as test_dict1 and concatenates the string values of test_dict1 and test_dict2 for each key. If a key is present only in test_dict1, its value is concatenated with an empty string.
  • Print the concatenated dictionary using the print() function.

Python3




# Python3 code to demonstrate working of
# Concatenate Dictionary string values
# Using a loop and the update() method
 
# Initialize dictionaries
test_dict1 = {'gfg': 'a', 'is': 'b', 'best': 'c'}
test_dict2 = {'gfg': 'd', 'is': 'e', 'best': 'f'}
 
# printing original dictionaries
print("The original dictionary 1 : " + str(test_dict1))
print("The original dictionary 2 : " + str(test_dict2))
 
# create an empty dictionary to store the result
res = {}
 
# loop through the keys in test_dict1
for key in test_dict1.keys():
     
    # check if the key is in test_dict2
    if key in test_dict2:
        # if the key is in both dictionaries, concatenate the values and add to res
        res.update({key: test_dict1[key] + test_dict2[key]})
    else:
        # if the key is only in test_dict1, add the value to res
        res.update({key: test_dict1[key]})
     
    # remove the key from test_dict2
    test_dict2.pop(key, None)
 
# add any remaining key-value pairs in test_dict2 to res
res.update(test_dict2)
 
# printing result
print("The string concatenation of dictionary is : " + str(res))


Output

The original dictionary 1 : {'gfg': 'a', 'is': 'b', 'best': 'c'}
The original dictionary 2 : {'gfg': 'd', 'is': 'e', 'best': 'f'}
The string concatenation of dictionary is : {'gfg': 'ad', 'is': 'be', 'best': 'cf'}

Time complexity: O(n), where n is the total number of key-value pairs in the two dictionaries.

Auxiliary space: O(n), where n is the total number of key-value pairs in the two dictionaries, because we are creating a new dictionary to store the result.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads