How to Convert Text to a Dictionary in Python?

Estimated read time 2 min read

To convert text to a dictionary in Python, you can use the json module to parse the text as JSON data. JSON (JavaScript Object Notation) is a widely used data format that represents structured data as key-value pairs. Here’s an example:

import json

text = '{"name": "John", "age": 30, "city": "New York"}'
dictionary = json.loads(text)

print(dictionary)  # Output: {'name': 'John', 'age': 30, 'city': 'New York'}

In this example, the json.loads() function is used to parse the text as JSON data and convert it into a dictionary. The resulting dictionary is assigned to the variable dictionary, which can then be used in your code.

Note that the input text must be properly formatted JSON for the conversion to succeed. If the text is not valid JSON, a json.JSONDecodeError will be raised. Make sure the text follows the JSON syntax, with key-value pairs enclosed in curly braces {} and separated by commas.

If you’re reading the text from a file, you can use the json.load() function instead, which reads the JSON data directly from a file object:

import json

with open('data.json') as file:
    dictionary = json.load(file)

print(dictionary)

In this example, the json.load() function reads the JSON data from the file specified by 'data.json' and directly converts it into a dictionary.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply