Str to dictionary python

How to Convert String to Dictionary in Python

To convert a string to a dictionary in Python, you can use the “json.loads()” function from the json module if the string is in a JSON-compliant format.

Example

import json str = '' print('The JSON String is', str) convertedDict = json.loads(str) print("After conversion: ", convertedDict) print(type(convertedDict))
The JSON String is After conversion:

You can see that the loads() function returns a dictionary, and we verified that using the type() method.

If the string is not in JSON format, you may need to parse it manually or use a custom parsing function depending on the specific format of the string.

Alternate methods

Using ast.literal_eval() function

The ast.literal_eval() is a built-in Python library function that converts a string to a dict.

To use the literal_eval() function, import the ast package and use its literal_eval() method.

import ast str = '' print('The JSON String is', str) convertedDict = ast.literal_eval(str) print("After conversion: ", convertedDict) print(type(convertedDict))
The JSON String is After conversion:

You can see that the output is the same as the loads() function, and it does the same thing.

Читайте также:  Factory pattern and abstract factory pattern in java

Using generator expressions in Python

If we have enough strings to form a dictionary, use the generator expressions to convert the string to a dictionary.

str = "E - 11, K - 19, L - 21" convertedDict = dict((x.strip(), int(y.strip())) for x, y in (element.split('-') for element in str.split(', '))) print("Converted dict is: ", convertedDict) print(type(convertedDict))

In this example, we have used many Python functions like dict(), strip(), int(), and split().

First, we split the string inside the for loop and converted them into a dictionary using the dict() method.

Next, the strip() method removes whitespace from the string and uses the int() function to convert the string to int for integer values.

Conclusion

The easiest way is to use the json.loads() function to convert a valid string to a dict in Python.

Источник

3 Ways to Convert String to Dictionary in Python

3 Ways to Convert String to Dictionary in Python

Converting one data type into another is a frequent problem in python programming and it is essential to deal with it properly. Dictionary is one of the data types in python which stores the data as a key-value pair. However, the exchange of data between the server and client is done by python json which is in string format by default.

As it is necessary to convert the python string to dictionary while programming, we have presented a detailed guide with different approaches to making this conversation effective and efficient. But before jumping on the methods, let us quickly recall python string and dictionary in detail.

What is Strings in Python?

Python string is an immutable collection of data elements. It is a sequence of Unicode characters wrapped inside the single and double-quotes. Python does not have a character data type and therefore the single character is simply considered as a string of length 1. To know more about the string data type, please refer to our article «4 Ways to Convert List to String in Python».

Check out the below example for a better understanding of strings in python

For Example

a = "Python Programming is Fun" print(a)
Python Programming is Fun 

What is Dictionary in Python?

A dictionary is an unordered collection of data elements that is mutable in nature. Python dictionary stores the data in the form of key-value pair.

Hence we can say that dictionaries are enclosed within the curly brackets including the key-value pairs separated by commas. The key and value are separated by the colon between them.

The most important feature of the python dictionaries is that they don’t allow polymorphism. Also, the keys in the dictionary are case-sensitive. Therefore, the uppercase and lowercase keys are considered different from each other. Later, you can access the dictionary data by referring to its corresponding key name.

Check out the below example for a better understanding of dictionaries in python.

For Example

sample_dict = < "vegetable": "carrot", "fruit": "orange", "chocolate": "kitkat" > print(sample_dict)

Convert String to Dict in Python

Below are 3 methods to convert string to the dictionary in python:

1) Using json.loads()

You can easily convert python string to the dictionary by using the inbuilt function of loads of json library of python. Before using this method, you have to import the json library in python using the “import” keyword.

The below example shows the brief working of json.loads() method:

For Example

import json original_string = '' # printing original string print("The original string is : " + str(original_string)) # using json.loads() method result = json.loads(original_string) # print result print("The converted dictionary is : " + str(result))
The original string is : The converted dictionary is :

2) Using ast.literal.eval()

The ast.literal.eval() is an inbuilt python library function used to convert string to dictionary efficiently. For this approach, you have to import the ast package from the python library and then use it with the literal_eval() method.

Check out the below example to understand the working of ast.literal.eval() method.

For Example

import ast original_String = '' # printing original string print("The original string is : " + str(original_String)) # using ast.literal_eval() method result = ast.literal_eval(original_String) # print result print("The converted dictionary is : " + str(result))
The original string is : The converted dictionary is :

3) Using generator expression

In this method, we will first declare the string values paired with the hyphen or separated by a comma. Later we will use the strip() and split() method of string manipulation in the for loop to get the dictionary in the usual format. Strip() method will help us to remove the whitespace from the strings. This method is not as efficient for the conversion of string to dictionary as it requires a lot of time to get the output.

Check out the below example for the string to dictionary conversion using a generator expression

For Example

original_String = "John - 10 , Rick - 20, Sam - 30" print("The original string is ",original_String) #using strip() and split() methods result = dict((a.strip(), int(b.strip())) for a, b in (element.split('-') for element in original_String.split(', '))) #printing converted dictionary print("The resultant dictionary is: ", result)
The original string is John - 10 , Rick - 20, Sam - 30 The resultant dictionary is:

Conclusion

String and dictionary data type has its own importance when it comes to programming in python. But when we wish to share the data over the network as a client-server connection, it is very important to convert a string into the dictionary for error-free data transfer. We have mentioned the three common methods to explicitly convert the string into a dictionary which will help you to make your programming faster and efficient. To learn more about dictionary and JSON in python, check our detailed guide on “5 Ways to Convert Dictionary to JSON in Python”.

Источник

String to Dictionary Python

In this tutorial, we will cover different ways to convert string to dictionary in Python.

Dictionary is one of the most commonly used data types in Python. It is an unordered collection of items of a key/value pair.

Most often, these dictionaries are stored as a string. For example, a dictionary can be stored as a string in JSON format.

To use them in Python, we first need to convert them into a dictionary. Luckily, Python provides us with multiple ways to do so.

Let’s see how we can convert a string to a dictionary in Python.

String to Dictionary Python

1. String to Dictionary using json module

Python provides a built-in module called json to work with JSON data. This module has multiple methods to deal with JSON data.

One of the methods is loads() which is used to convert a string to a dictionary.

Start with importing the json module. Then, use the loads() method to convert the string to a dictionary.

import json str = '' d = json.loads(str) print(d) print(type(d))

2. String to Dictionary using ast.literal_eval()

Python has another module called ast that is used to work with Abstract Syntax Trees. This module has a method called literal_eval() that evaluates literal Python expressions and returns the value.

Means it can evaluate a string containing a Python expression and return the value.

Let’s use this method to convert a string to a dictionary.

import ast str = '' d = ast.literal_eval(str) print(d) print(type(d))

Note : This method is not safe to use. It can evaluate any Python expression. So, it can be dangerous if you are using it with untrusted input.

3. String to Dictionary using eval() function

eval() is a built-in function in Python that can evaluate any Python expression given as a string.

Just like previous method, this method can also be used to convert a string to a dictionary.

Let’s see how we can do it.

str = '' d = eval(str) print(d) print(type(d))

Both ast.literal_eval() and eval() evaluates any Python expression given as string but ast.literal_eval() is limited evaluating only literal Python expressions.

4. Using Custom Function

Above we have looked at 3 different build-in methods to convert a string to a dictionary. But, if you want to use a custom function, you can do so.

Here is a custom function that can be used to convert a string to a dictionary.

def string_to_dict(s): try: d = <> s = s.strip() if s[0] != '': return None s = s[1:-1] key_value_pairs = s.split(',') for pair in key_value_pairs: key_value = pair.split(':') if len(key_value) != 2: return None key = key_value[0].strip() value = key_value[1].strip() if (key[0] == '"' and key[-1] == '"') or (key[0] == "'" and key[-1] == "'"): key = key[1:-1] if (value[0] == '"' and value[-1] == '"') or (value[0] == "'" and value[-1] == "'"): value = value[1:-1] dStr to dictionary python = value return d except: return None str = '' d = string_to_dict(str) print(d) print(type(d))

The above function converts a string to a dictionary in the following steps:

  • First, it checks if the string is a valid dictionary string. If not, it returns None .
  • Then, remove the curly braces from both ends
  • Splits the string into key-value pairs using split() method and loop through each pair.
  • Now split each pair into key and value
  • Finally, it adds the key-value pair to the dictionary.

Conclusion

We have seen 4 different ways to convert a string to a dictionary in Python. All the methods are explained with examples.

Among all the methods, json.loads() is the most popular and recommended method because it safely converts a string to a dictionary.

However, if you want to use a custom function, you can use the function we have created in this tutorial.

Now, it’s your turn to use them for real world applications.

Источник

Оцените статью