Convert A Unicode String To A Dictionary In Python

Below are some ways by which we can convert Unicode string to a dictionary in Python:

Convert A Unicode String To A Dictionary Using json.loads()

Utilizing the `json` module’s `loads()` function is a straightforward and effective way to convert a JSON-formatted Unicode string into a Python dictionary.

Python3




import json
 
unicode_string = '{"name": "John", "age": 30, "city": "New York"}'
print(type(unicode_string))
 
result_dict = json.loads(unicode_string)
print(type(result_dict))
print(result_dict)


Output

<class 'str'>
<class 'dict'>
{'name': 'John', 'age': 30, 'city': 'New York'}


Unicode String to Dictionary Using ast.literal_eval() Function

The `ast.literal_eval()` function is used as a safer alternative to `eval()`, allowing the evaluation of literals and converting the Unicode string to a dictionary.

Python




import ast
 
unicode_string = '{"key1": "value1", "key2": "value2", "key3": "value3"}'
print(type(unicode_string))
 
result_dict = ast.literal_eval(unicode_string)
print(type(result_dict))
print(result_dict)


Output

<type 'str'>
<type 'dict'>
{'key3': 'value3', 'key2': 'value2', 'key1': 'value1'}


Convert Unicode String to Dictionary Using yaml.safe_load() Function

The `yaml.safe_load()` function can handle YAML-formatted Unicode strings, providing a versatile alternative for converting data into a dictionary.

Python




import yaml
 
unicode_string = "name: Alice\nage: 25\ncity: Wonderland"
print(type(unicode_string))
 
result_dict = yaml.safe_load(unicode_string)
print(type(result_dict))
print(result_dict)


Output:

<type 'str'>
<type 'dict'>
{'name': 'Alice', 'age': 25, 'city': 'Wonderland'}

Convert Unicode String to Dictionary in Python

Python’s versatility shines in its ability to handle diverse data types, with Unicode strings playing a crucial role in managing text data spanning multiple languages and scripts. When faced with a Unicode string and the need to organize it for effective data manipulation, the common task is converting it into a dictionary. In this article, we will see how to convert a Unicode string to a dictionary in Python.

Similar Reads

Convert A Unicode String To A Dictionary In Python

Below are some ways by which we can convert Unicode string to a dictionary in Python:...

Conclusion

...