Strings are used to ship/talk information over the community, however when this string is acquired by a program, it must be transformed into a knowledge sort that helps quicker manipulations. In Python, there are dictionaries that permit the consumer to retailer information within the type of pairs or key-pair values. These are similar to JSON, and on this publish, you’re going to discover ways to convert a Python String right into a dictionary.
The content material of this information is as follows:
Let’s begin with the primary technique straight away.
Technique 1: Utilizing the json.masses() Technique to Convert String Into Dict
The hundreds() technique is used to “load” a JSON string and convert it right into a JSON, or in Python, a Dictionary. Nonetheless, for this technique to work, the string must be within the particular format through which every “key” is encapsulated by citation marks, separated by a colon from the “worth”. And each pair is separated by a comma.
To display the working of the hundreds() technique for string-to-dictionary conversion, use the next code snippet:
stringVar = ‘{“Title”:”John Doe”, “Age” : “20”, “Occupation”: “Physician”}’
resultVar = json.masses(stringVar)
print(“Preliminary String: “,stringVar)
print(“After Conversion: “,resultVar)
print(“Sort After Conversion: “,sort(resultVar))
On this code snippet:
- The “json” module is imported in order that the consumer can make the most of the hundreds() technique.
- After that, the string “stringVar” is initialized
- The hundreds() technique is utilized on the stringVar and the result’s saved within the “resultVar” variable
- Lastly, the unique string, the resultVar, and the kind of the resultVar are printed onto the terminal.
When this code is executed, it produces the next final result on the terminal:
On this output, you may simply discover that the string has been efficiently transformed to a dict information sort in Python.
Technique 2: Utilizing the ast.literal_eval() Technique to Convert String Into Dict
The literal_eval() technique from the “ast” package deal will also be used to do precisely the identical job as the hundreds() technique from the “json” package deal. To make use of this technique, check out the next code:
stringVar = ‘{“Title”:”John Doe”, “Age” : 20, “Occupation”: “Physician”, “Wage” : 40000}’
resultVar = ast.literal_eval(stringVar)
print(“Preliminary String: “,stringVar)
print(“After Conversion: “,resultVar)
print(“Sort After Conversion: “,sort(resultVar))
When this code is executed, it can produce the next outcome on the terminal:
The output verifies that the string has been efficiently transformed right into a Python Dict.
Technique 3: Utilizing the eval() Technique to Convert String Into Dict
One other very comparable technique is the eval() technique which is used to guage whether or not a string is accurately formatted or not and returns the transformed dictionary again to the caller. To see its working, take the next code instance:
resultVar = eval(stringVar)
print(“Utilizing the eval() Technique”)
print(“Preliminary String: “,stringVar)
print(“After Conversion: “,resultVar)
print(“Sort After Conversion: “,sort(resultVar))
When this code is executed, it can produce the next output on the terminal:
You’ve gotten efficiently transformed a Python String right into a Python dict utilizing the eval() technique.
Technique 4: Utilizing strip() and cut up() in Generator Expressions
Suppose that the string isn’t within the JSON String format, and you continue to wish to convert it right into a Python Dict. For this goal, you would need to make the most of numerous string manipulation strategies like strip() and cut up(). For instance, suppose the string comprises key-value pairs, through which the important thing and worth are separated by a hyphen “–”, and every pair is separated by a comma. For instance, that is the string to be transformed:
stringVar = “Title – John Doe , Age – 20 , Occupation – Physician, Martial_Status – Single”
To do that, the consumer can make the most of the generator expression, check out the next code:
resultVar = dict((a.strip(),b.strip())
for a,b in (part.cut up(“-“)
for part in stringVar.cut up(“,”)))
print(“Preliminary String: “,stringVar)
print(“AfterConversion: “,resultVar)
print(“Sort After Conversion: “,sort(resultVar))
To grasp this code, begin from the innermost loop:
- The string is slit on each incidence of a comma to get particular person key-pairs
- For each key-pair substring, the string is cut up on the incidence of a hyphen “–” and the 2 sections are allotted to variables “a” and “b”. The “a” holds the important thing half, whereas the “b” holds the worth half.
- The strip() technique is utilized on each variables “a” and “b” to take away any clean areas earlier than or after the string.
- After that, each of those variables are handed into the dict() technique to create a brand new Dictionary variable, “resultVar”
- Lastly, print the unique string and the transformed variable resultVar and its sort onto the terminal utilizing the print technique()
When this code is executed, it produces the next output:
It may be simply noticed that the string has been transformed right into a Python dict.
Conclusion
To transform a string right into a Python “dict”, the consumer can use the hundreds() technique from the “json” package deal or the literal_eval() technique from the “ast” package deal. Nonetheless, to make use of these two strategies, the string must be a JSON String. Apart from this, if the string is in a distinct format, then the consumer must use a mixture of assorted string manipulation strategies to give you a working generator expression.