How to Convert Dictionary to Concatenated String using Python?


A dictionary in Python is a built-in data structure that allows you to store and retrieve values using unique keys. It is an unordered collection of key-value pairs enclosed in curly braces {}. Dictionaries provide a convenient way to organize and manipulate data, making it easy to access values based on their corresponding keys.

In this article, we are going to see how to convert Dictionary to Concatenated String using Python which means that all the keys and values of the dictionary will be combined in the form of a string as follows.

Input = {'one': 1, 'two': 2, 'three': 3}
Output = one1two2three3

Let us now see some of the methods in detail.

Method 1: Using a Loop and F-string (Naïve Method)

This method simply uses a for each loop to iterate over the entire dictionary’s keys and values and appends to them to a string which is initially created as an empty string.

Example

dictionary = {'one': 1, 'two': 2, 'three': 3}
concatenated_string = ''
for key, value in dictionary.items():
   concatenated_string += f"{key}{value}"
print(concatenated_string)

Output

one1two2three3

Method 2: Using a List Comprehension and Join() Method

List comprehension is an elegant feature in Python that makes creating new lists easy by iterating over an existing iterable (such as a list, tuple or dictionary) while applying transformations or conditions. Essentially it makes the creation and iteration process one-liner code!

The join() method, as the name suggests is used to join or concatenate the elements of an iterable. Since join() is a string method, its input iterable (such as a list, tuple, or generator) are provided as its argument and a single string is returned wherein all the elements of the iterable are “joined”

Its syntax is as follows −

string = separator.join(iterable)
  • separator  Represents the string that will be used to separate the elements in the final concatenated string. It can be an empty string or any desired separator.

  • iterable  Represents the iterable object whose elements will be joined together into a string.

The join() method is often used in conjunction with list comprehension to concatenate strings efficiently. It eliminates the need for explicit iteration and string concatenation in a loop, resulting in cleaner and more optimized code.

Example

dictionary = {'apple': 3, 'banana': 2, 'cherry': 5}
concatenated_string = ''.join([key + str(value) for key, value in dictionary.items()])
print(concatenated_string)

Output

apple3banana2cherry5

Method 3: Using Map() and Join() Methods

The map() function applies a specified function to each element in an iterable, returning an iterator that yields transformed values. Lazily computing these values as you iterate over this iterator yields results which change on-demand as you iterate over iterators that contain these transformed values.

The syntax of map() is as follows −

map(function, iterable1, iterable2, ...)
  • function  Represents the function that will be applied to each element in an iterable. It could be one of several types: built-in function, lambda function or user defined function.

  • iterable1, iterable2, etc.  Represents one or more iterables that hold elements to be processed by the function, either having equal lengths or variable sizes.

A Lambda function (also referred to as anonymous function) is a small and concise function created with the lambda keyword and used for simple one-line operations.

Example

dictionary = {'red': 1, 'green': 2, 'blue': 3}
concatenated_string = ''.join(map(lambda x: x[0] + str(x[1]), dictionary.items()))
print(concatenated_string)

Output

red1green2blue3

Method 4: Using Reduce() from the Functools Module

The commonly known functools module of python consist of a reduce() function which is used to perform a cumulative computation on a sequence of elements thereby reducing them to a single value. It repeatedly applies a function to the elements of the sequence, accumulating the result.

Syntax of reduce() is as follows −

result = reduce(function, sequence, initial_value)
  • function  Represents the function to be applied to the elements. It should take two arguments and return a single value. The function is applied cumulatively to the items of the sequence.

  • sequence  Represents the iterable sequence of elements to be reduced.

  • initial_value  (optional) Represents the initial value for the accumulation. If not provided, the first two elements of the sequence will be used as the initial values.

Example

from functools import reduce

dictionary = {'A': 10, 'B': 20, 'C': 30}
concatenated_string = reduce(lambda x, y: x + y[0] + str(y[1]), dictionary.items(), '')
print(concatenated_string)

Output

A10B20C30

Method 5: Using Regular Expression

Regex (Regular Expressions), more commonly referred to by its acronym regex, are strings of characters used to specify search patterns. With regex you can easily search for specific patterns, validate input, extract information from documents and complete complex text processing tasks using metacharacters, quantifiers and predefined character classes.

Example

import re

dictionary = {'number1': 1, 'number2': 2, 'number3': 3}
concatenated_string = ''.join(re.findall(r'(\w+)', str(dictionary)))
print(concatenated_string)

Output

number11number22number33

Method 6: Using Reduce() and Operator.concat

The reduce() function takes two arguments; the function to be applied and the iterable to which it is supposed to be applied to. It performs a cumulative computation on the elements of the iterable by applying the function to pairs of elements successively, reducing them to a single value. In this case, the concat() function is used as the function argument for concatenation.

The concat() function from the operator module is a convenience function that performs string concatenation. It takes two string arguments and returns their concatenated version.

Example

from functools import reduce
from operator import concat

dictionary = {'dog': 3, 'cat': 2, 'bird': 1}

#concat is the input function for reduce.
concatenated_string = reduce(concat, (key + str(value) for key, value in dictionary.items()))
print(concatenated_string)

Output

dog3cat2bird1

Method 7: Using Chain() from the Itertools Module

The itertools module consist of a chain() function which is used to combine multiple iterable into 1 single iterable sequence. The resulting iterable contains all the elements from each input iterable, in the same order as they appear.

Its syntax is −

result = chain(iterable1, iterable2, ...)

The chain() function concatenates the input iterables without making any copies of their elements. It efficiently produces a single iterator that sequentially iterates over each element of the input iterables, one after another, until all elements have been exhausted.

Example

from itertools import chain

dictionary = {'red': 1, 'green': 2, 'blue': 3}
concatenated_string = ''.join(chain.from_iterable((key, str(value)) for key, value in dictionary.items()))
print(concatenated_string)

Output

red1green2blue3

Conclusion

In this tutorial, we have explored various different techniques that can be used for turning dictionaries into concatenated strings in Python. They include loops and string concatenation; list comprehension with join() method; map() with join(); reduce() operator.concat, regular expressions and chain() from itertools module. At the end of the day, they all have the same output; to combine the elements of the iterable into 1 single string.

Updated on: 18-Aug-2023

80 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements