Open In App

Python – Convert Dictionary to Concatenated String

Last Updated : 11 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Dictionaries, we can have a task in which we need to perform the conversion of converting dictionary to string, which is concatenated key-value pair. This can have application in domains in which we require to reduce storage space or require strings as target data. Let’s discuss certain ways in which this task can be performed.

Method 1: Using an empty string + for loop

In this method, we will use a for loop to iterate through the dictionary object and keep on adding the key: value pairs to the empty string.

Python3




# Python3 code to demonstrate working of
# Convert Dictionary to Concatenated String
# Using an empty string + for loop
 
# initializing dictionary
test_dict = {'gfg': 1, 'is': 2, 'best': 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Create an empty string
res = ' '
 
# Convert Dictionary to Concatenated String
# Using for loop and empty string
for item in test_dict:
    res += item + str(test_dict[item])
 
# printing result
print("The dictionary after concatenation is : " + str(res))


Output

The original dictionary is : {'gfg': 1, 'is': 2, 'best': 3}
The dictionary after concatenation is :  gfg1is2best3

Method 2 : Using join() + items() 

The combination of above functions can be used to solve this problem. In this, we need to perform the task of concatenation using join() and extraction of dictionary items is done using items().

Python3




# Python3 code to demonstrate working of
# Convert Dictionary to Concatenated String
# Using join() + items()
 
# initializing dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert Dictionary to Concatenated String
# Using join() + items()
res = ''.join(key + str(val) for key, val in test_dict.items())
 
# printing result
print("The dictionary after concatenation is : " + str(res))


Output

The original dictionary is : {'gfg': 1, 'is': 2, 'best': 3}
The dictionary after concatenation is : gfg1is2best3

Method 3 : Using reduce() + lambda 

The combination of above functions can be used to perform this task. In this, we perform the task of concatenation using combination of reduce() and lambda.
 

Python3




# Python3 code to demonstrate working of
# Convert Dictionary to Concatenated String
# Using reduce() + lambda
from functools import reduce
 
# initializing dictionary
test_dict = {'gfg' : 1, 'is' : 2, 'best' : 3}
 
# printing original dictionary
print("The original dictionary is : " + str(test_dict))
 
# Convert Dictionary to Concatenated String
# Using reduce() + lambda
res = reduce(lambda key, val : key + str(val[0]) + str(val[1]), test_dict.items(), '')
 
# printing result
print("The dictionary after concatenation is : " + str(res))


Output

The original dictionary is : {'gfg': 1, 'is': 2, 'best': 3}
The dictionary after concatenation is : gfg1is2best3

Method#4: Using list comprehension with zip() function

Steps:

  1. Define the input dictionary
  2. Uses the zip() function to iterate over the keys and values of the dictionary in parallel.
  3. Uses a list comprehension to concatenate each key-value pair into a string using the + operator and the str() function.
  4. Joins the resulting list of strings using the join() method.
  5. Prints the concatenated string.

Python3




# Define the input dictionary
my_dict = {'gfg': 1, 'is': 2, 'best': 3}
 
# Convert dictionary to concatenated string using a list comprehension with zip() function
concatenated_string = ''.join([str(x) + str(y) for x, y in zip(my_dict.keys(), my_dict.values())])
 
# Print the concatenated string
print("The dictionary after concatenation is : ", concatenated_string)


Output

The dictionary after concatenation is :  gfg1is2best3

Time Complexity: O(n). The zip() function in this approach has a time complexity of O(n), where n is the number of items in the dictionary. The list comprehension has a time complexity of O(n), where n is the number of items in the dictionary. The join() method has a time complexity of O(n), where n is the length of the resulting string.
Auxiliary Space: O(n). This approach creates a list of strings using a list comprehension, which has a space complexity of O(n), where n is the number of items in the dictionary. The join() method also creates a new string object, which has a space complexity of O(n), where n is the length of the resulting string.

METHOD 5: Using the map() function 

APPROACH:

Using the map() function with a lambda function to concatenate the keys and values into a single string, and then using the join() method to concatenate the resulting list into a single string.

Steps:

  1. Create a dictionary.
  2. Use the map() function with a lambda function to concatenate each key and value pair into a single string.
  3. Convert the resulting map object into a list.
  4. Use the join() method to concatenate the strings in the list into a single string.
  5. Return the final concatenated string.

Python3




# Initializing dictionary
my_dict = {'gfg': 1, 'is': 2, 'best': 3}
 
# Concatenate keys and values into a list
# using map() with a lambda function
result_list = list(map(lambda x: x[0] + str(x[1]), my_dict.items()))
 
# Concatenating the list items into a single string
result = "".join(result_list)
 
# Printing answer
print(result)


Output

gfg1is2best3

Time complexity: O(n), where n is the number of items in the dictionary. The map() function, list conversion, and join() method all have a time complexity of O(n), so the overall time complexity is O(n).
Auxiliary Space: O(n), where n is the number of items in the dictionary. The map() function creates a map object that requires O(n) space, and the resulting list also requires O(n) space. The final concatenated string requires O(n) space as well. So the overall space complexity is O(n).

METHOD 6: Using re.sub() method

Intuition: We use the re.sub() function to remove all non-alphanumeric characters from the string representation of the given dictionary.

Steps:

  1. Import the re module.
  2. Define a dictionary my_dict.
  3. Convert the dictionary to a string using str() function.
  4. Apply the re.sub() function to the string with regex pattern r’\W+’ to remove all non-word characters.
  5. Store the resulting string in the variable result.
  6. Print the value of the result.

Python3




import re
 
# Initializing list
my_dict = {'gfg': 1, 'is': 2, 'best': 3}
 
result = re.sub(r'\W+', '', str(my_dict))
 
# Printing answer
print(result)


Output

gfg1is2best3

Time Complexity: O(N), where n is the length of the resulting string. This is because the re.sub() function iterates through each character in the string once.
Auxiliary Space: O(N), where n is the length of the resulting string. This is because we create a new string that contains only alphanumeric characters.

Method 7: Using generator expression +  join function 

Steps:

  1. Use a generator expression that iterates over the key-value pairs in the dictionary, and concatenates them using string concatenation.
  2. Pass the generator expression to the join function to join the concatenated strings into a single string.
  3. Print the final concatenated string.

Python3




# Iniializing dictionary
my_dict = {'gfg': 1, 'is': 2, 'best': 3}
 
# Concatenate keys and values into a single string
# using generator expression and join function
result = "".join(key + str(value) for key, value in my_dict.items())
 
# Pinting answer
print(result)


Output

gfg1is2best3

The time complexity of this method is O(n), where n is the number of key-value pairs in the dictionary. 

The auxiliary space used is O(n), where n is the length of the final concatenated string.



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

Similar Reads