How to Convert a Dict to String in Python[5 ways]

In this Python tutorial, we will discuss “How to convert a dict to string in Python” with different approaches and built-in methods.

Convert a Dict to String in Python

When I needed to store all the JSON data (dictionary) in the text file, I was looking for a way to convert a dict to a string in Python, and I found 5 different methods and techniques that helped me out.

Suppose there is a dictionary like this “state= {“California”: 39512223, “Texas”: 29145505, “Florida”: 21538187,” New York”: 19453561}” and if we convert this into a string, still it looks the same as a dictionary, but when you check the type of the “state”, it seems like
<class> ‘str’

How to convert a dict to string in Python using json.dumps() method

To convert a dict to a string in Python, we will use the dumps() method from the json module. This method converts Python objects like dict, list, tuple, etc., into the JSON string. So, we’ve used json.dump() to convert a dict to a string in Python.

Syntax

json.dump(object)
  • json.dump(object): Calling dump() method from json module in Python, and you can give any object like dict, int, list, etc., as a parameter

Let’s understand how we can use json.dump() to convert dict to string in Python.

import json

usa_state_population = {"California": 39512223,"Texas": 29145505,"Florida": 21538187,"New York": 19453561}

print ("Original Dictionary = ", usa_state_population)
print (type(usa_state_population))

converted_result = json.dumps(usa_state_population)

print ("\nConverted into string = ", converted_result)
print (type(converted_result))
How to convert a dictionary to string in Python using json.dumps() method

In the above code, we have data of state and its population as a dictionary key-value pair and we needed to convert it into a string, so we’ve used json.dumps() method, where we’ve given “usa_state_population” as parameter like this “json.dumps(usa_state_population)“.

READ:  Get URL parameters in Django

After type conversion, we’ve checked the type of “converted_result” and we are getting “<class ‘str’>” as an output.

Python convert dict to string using the str() method

We can use a built-in method called str() in Python, which is the direct and easiest way to convert any data into a string in Python. This method also required an object as a parameter.

Syntax

str(object)
  • str(object) : This method also accepts 2 more optional parameters named
    encoding = encoding and error = error.
  • According to our requirement, the object is a dictionary, so we will use this method to convert a dictionary to a string in Python.

Let’s take one practical example to convert Python dict to str using the str() method.

car_data =     {
    "Ford": "Mustang",
    "Chevrolet": "Camaro",
    "Dodge": "Challenger",
    "Toyota": "Camry",
    "Honda": "Accord"
}
print(f"Original Dictionary: {car_data}")
print(type(car_data))

converted_result = str(car_data)

print(f"Converted to string: {converted_result}")
print(type(converted_result))
Python convert dict to string using str() method

In the above code, we have a dataset of cars in the key-value pair as car name and model, and then we used “str(car_data)” to convert a dict to a string in Python.

Program to convert dict to String in Python using pformat() method of pprint module

The pformat() method from the pprint module returns a formatted representation of any object in string format. So, we will use this method to convert a dict to a string in Python.

Syntax

pprint.pformat(object)
  • pprint.pformat(object): Here, pprint is a built-in module and pformat() is a method, it requires an object as a parameter.
import pprint

employees_data = names = {
    "Oliver": 25,
    "Amelia": 23,
    "Harry": 21,
    "Olivia": 19,
    "Jack": 17
}
print(f"Original dictionary: {employees_data}")
print("Type: ",type(employees_data))

converted_result = pprint.pformat(employees_data)

print(f"\nConverted to string: {converted_result}")

print("Type: ",type(converted_result))
Program to Convert dict to String in Python using pformat() method of pprint module

The above code has “employees data” in the key-value pair, such as their name and age. Then we used the pformat() method “pprint.pformat(employees_data)” to convert a dict to a string in Python.

READ:  Python Scipy Interpolate

Convert a Python dict to a string using for loop

When we need to convert dict to str without using any built-in Python method, we can use a for loop to get the desired output.

When you use for loop in the dictionary, it iterates to every key in sequence, and then you can concat it to the string to convert a dict to a string in Python.

country_dialing_code = {
    "United States": "+1",
    "India": "+91",
    "China": "+86",
    "Indonesia": "+62",
    "Brazil": "+55"
}
print(f" Original Dictionary - {country_dialing_code}")
print(type(country_dialing_code))

str = ""

for item in country_dialing_code:
    str += item + ': ' + country_dialing_code[item] + ', '

print(f"\nConverted string - {str}")
print(type(str))
Convert a python dict to a string using for loop

In the above code, we have the data of the country dialling code in the key-value pair. So first, we’ve initialized “str = ” ” empty var for string.

Then, we initialized a loop to iterate over every dictionary key.
“for item in country_dialing_code”. Then we concatenated it with an empty string: “str += item + ‘: ‘ + country_dialing_code[item] + ‘, ‘.

How to convert dict to str using items() with join() method

Again, we are performing concatenation using join() in Python and the items() method of a dictionary, which is used to get all the keys and the values in a list of tuples format like this [(key, value), (key, value)]of the dictionary.

So, we will target all keys and values with the help of a one-liner for loop.

Syntax

.join(key +' : '+ value for key, value in dict.items())
  • for key, value in dict.Items (): The loop will first perform in syntax, where two variables named key and value are initialized. And dict.items() will return a list of tuples as
    a key-value pair.
  • key +’ : ‘+ value: Then it will perform this part of the code, where we format the key and value as per our requirement.
  • .join(key +’ : ‘+ value for key, value in dict.items()): And Finally it will perform the join() method to concatenate with the string.
car_data = {
    "Honda": "Accord",
    "Nissan": "Altima",
    "Hyundai": "Elantra",
}
print(f"Given car_dataionary: {car_data}")
print("Type: ",type(car_data))

converted_data = ', '.join(key +' : '+ value for key, value in car_data.items())

print(f"Converted converted_dataing: {converted_data}")
print('Type: ',type(converted_data))
How to convert dict to str using items() with join() method

In the above code, the car data is in dictionary format, with the company name as the key and the model name as the value.

READ:  NumPy random number between two values in Python [3 Methods]

To convert it into strings, we’ve used the items() method “ for key, value in car_data.items()” to get all the keys and values in the form of a list of tuples and used the join() method to concatenate with the comma-separated string “‘, ‘.join(key +’ : ‘+ value for key, value in car_data.items())“.

Conclusion

I hope you understand all the approaches we’ve used to convert a dict to a string in Python. We’ve explored 5 different methods, such as json.dumps(), str(), pformat(), etc., and techniques like using looping statements to get the desired output.

You may like to read: