fjjones88
fjjones88

Reputation: 349

Converting String to Python Dictionary

This code returns a str as the type. Given the format of tasks, how do I convert it into a python dictionary?

import json

tasks = '''{'key1': 'val1', 'key2': None}'''

new_tasks = tasks.replace("'", "\"")
new_tasks = new_tasks.replace('None', 'null')

new_tasks = json.dumps(new_tasks)
new_tasks = json.loads(new_tasks)
print(type(new_tasks))

Note: I would prefer to not use ast.literal_eval or ast.eval.

Upvotes: 0

Views: 78

Answers (1)

user16401871
user16401871

Reputation:

import json

tasks = '''{'key1': 'val1', 'key2': None}'''

new_tasks = tasks.replace("'", "\"")
new_tasks = new_tasks.replace('None', 'null')

# new_tasks = json.dumps(new_tasks)
new_tasks = json.loads(new_tasks)
print(type(new_tasks))

As Barmar said, the dumps double wraps it in quotation marks

output:

<class 'dict'>

Upvotes: 1

Related Questions