Python offers a variety of data types for storing values in various formats, including strings, dictionaries, lists, and more. While programming, you will come across the problem of converting one data type to another.
Dictionary is a convenient format to store and map data. Its key-value format makes it easier to map data. If you want to store a dictionary's data in a file or database, a string is a more convenient format for storage.
Furthermore, if you're familiar with JSON files, you must be aware that text is one of the permitted forms for storing data in JSON. As a result, dictionaries must be converted into strings and vice versa.
In this article, we'll look at methods for converting a dictionary to a string in Python.
What is a Dictionary in Python?
A dictionary is a mutable data type in Python, that stores data in the form of key-value pairs.
The basic syntax for a dictionary is:
dictionary = {'key' : 'value' , 'key2' : 'value2' }
(key and value can be different data types. Here, assume that they are strings)
Also, the keys and values in the dictionary are case-sensitive, hence it detects uppercase and lowercase of the same alphabet to be different.
For example:
# declaring a dictionary dictionary = {"book": "The Invisible Man", "class": 12, "grade": "A"} # note the key-value pair of 'class' (string) and 12 (integer) print(dictionary)
Output:
{'book': 'The Invisible Man', 'class': 12, 'grade': 'A'}
The above example also depicts that we can use different data types to form a key-value pair in a dictionary. You can also access the values using their associated keys in a dictionary. For example:
# declaring a dictionary dictionary = {"book": "The Invisible Man", "class": 12, "grade": "A"} print(dictionary) # accessing value 12 print("Class : ", dictionary["class"])
Output:
{'book': 'The Invisible Man', 'class': 12, 'grade': 'A'} Class : 12
What is a String in Python?
A string is an immutable data type in Python. Any text (including alphabets, special characters, or numbers) enclosed within quotation marks (double or single in Python) is known as a string in Python. This is the most used data type in any programming language.
For example:
# initializing a string string = 'Ways to convert dict to string in Python' print(string)
Output:
Ways to convert dict to string in Python
To know more about the String data type, please check 4 Ways to Convert List to Strings in Python.
What is the Conversion of Dict to String in Python?
After learning about dictionaries and strings, you must be wondering about the end results of this conversion. As what result will we obtain from this conversion?
Don't worry, let me put this in simple words. We have to convert a dictionary, enclosed within curly brackets, to strings, enclosed between quotation marks.
For example:
# a dictionary dictionary = {1: "A", 2: "B", 3: "C"} print("Dictionary: ", dictionary, " type: ", type(dictionary)) # a string string = "1: A, 2: B" print("String: " + string + " type: ", type(string))
Output:
Dictionary: {1: 'A', 2: 'B', 3: 'C'} type: <class 'dict'> String: 1: A, 2: B type: <class 'str'>
Note that the dictionary gets printed as it is (i.e. as declared) whereas strings avoid quotation marks. You'll be able to differentiate them as you go down the article.
Also, learn how to convert String to Dict in Python.
How to Confirm the Conversion of Dict into String in Python?
Let me tell you the simplest and easiest method to do so: Try accessing the values using their assigned keys for a better understanding (You can always use the type() method).
Pretty easy, right?
Let's take an example for better understanding:
# a dictionary dictionary = {1: "A", 2: "B", 3: "C"} print("Dictionary: ", dictionary, " type: ", type(dictionary)) # calling upon str() to convert dict to string (You'll learn it soon) string = str(dictionary) print("Dict into stringa: " + string + " type ", type(string)) # access value 'A' from key 1 in dictionary print("key = 1 value = ", dictionary[1]) # try accessing 'A' from the string using same format as above print("key = 1 value = ", string[1])
Output:
Dictionary: {1: 'A', 2: 'B', 3: 'C'} type: <class 'dict'> Dict into stringa: {1: 'A', 2: 'B', 3: 'C'} type <class 'str'> key = 1 value = A key = 1 value = 1
Note the difference between the output when we try to access the value using keys. This confirms the conversion of dict to string in Python.
Now, you must be wondering why did it give '1' at string[1]? This is because of "indexing". Indexing in Python begins from 0. When converting dict into strings in Python, the dictionary's curly brackets are also converted to be a part of the strings. Hence, after this conversion, the opening bracket marks the beginning of the string and hence, is assigned an index = 0.
Have a look at the image below to get a clear understanding:
The image gives you a better idea of indexing after conversion of the dictionary in string.
3 Ways to Convert Dict to String in Python
Given below are a few methods to convert dict to string in Python.
01) Using str() function
You can easily convert a Python dictionary to a string using the str() function. The str() function takes an object (since everything in Python is an object) as an input parameter and returns a string variant of that object. Note that it does not do any changes in the dictionary itself but returns a string variant.
Let's take a brief example to show the use of the str() function:
# a dictionary dictionary = {1: "A", 2: "B", 3: "C"} print("Dictionary: ", dictionary, " type: ", type(dictionary)) # calling upon str() to convert dict to string string = str(dictionary) print("Dict into stringa: " + string + " type ", type(string))
Output:
Dictionary: {1: 'A', 2: 'B', 3: 'C'} type: <class 'dict'> Dict into string: {1: 'A', 2: 'B', 3: 'C'} type <class 'str'>
From the above example, you can note that the type shifts from 'dict' to 'str' for the dictionary after conversion.
02) Using json.dumps() method
Another method to convert a dictionary into a string in Python is using the dumps() method of the JSON library. The dumps() method takes up a JSON object as an input parameter and returns a JSON string. Remember! To call the dumps() method, you need to import the JSON library (at the beginning of your code).
Let's take an example below:
# importing the dumps method from json library from json import dumps # declaring a dictionary dictionary = {"book": "The Invisible Man", "class": 12, "grade": "A"} print("Dictionary: ", dictionary) # conversion converted = dumps(dictionary) print("Dict to string: " + converted + " type: ", type(converted))
Output:
Dictionary: {'book': 'The Invisible Man', 'class': 12, 'grade': 'A'} Dict to string: {"book": "The Invisible Man", "class": 12, "grade": "A"} type: <class 'str'>
Also, there's the pickle module in python, which provides the same functionality. The use of JSON is preferred over pickle since JSON has cross-platform support.
03) Using the Conventional Way
Apart from using the in-built functions, you can always convert a dict to a string in Python using the conventional way. The conventional way is the use of a for loop to iterate over the dictionary and concatenate the newly formed strings.
Hence, it involves two operations:
- Iterating over the dictionary using for loop
- Concatenating strings
Let's take an example for better understanding:
# declaring dict from multiprocessing.sharedctypes import Value dictionary = {"a": "A", "b": "B", "c": "C"} print("Dictionary: ", dictionary) # an empty string converted = str() # iterating over dictionary using a for loop for key in dictionary: converted += key + ": " + dictionary[key] + ", " print("The obtained string: " + converted + " type: ", type(converted))
Output:
Dictionary: {'a': 'A', 'b': 'B', 'c': 'C'} The obtained string: a: A, b: B, c: C, type: <class 'str'>
This method is not recommended to convert a dictionary into a string. This involves storing the concatenated forms of the key-value pairs into strings (also missing out on the brackets!). Various versions of this method are used to convert only the dictionary keys or values into a string.
Now, you check our article on Dictionary to JSON.
Conclusion
Conversion of a data type to another is an often encountered problem. Sometimes this may include serialization and deserialization, pointing towards the 'pickle module'. The above-listed methods include Python in-built methods as well as the conventional approach to explicitly convert a dictionary to a string in Python.