Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

python unable to get dictionary from string

I have a subprocess that prints a string that I would like to use as a dictionary.

b"{'name': 'Bobby', 'age': 141}\r\n"

I am decoding the output using.

d = p.stdout.read().decode("utf-8").strip()

Why am I unable to use it as a dictionary? d['name'] returns TypeError: string indices must be integers

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Does anyone know what is going on? Is it some kind of encoding issue?

Cheers,
Chris

>Solution :

Use the inbuilt json module; speficially, json.loads().

json.loads() inputs a string/text object and returns a Python dictionary. JSON’s syntax uses double quotes for keys and values, however, so you’d need to reformat your string to use double quotes instead of single quotes:

'{"name": "Bobby", "age": 141}\r\n'

Then we can use the json module:

import json

my_string = '{"name": "Bobby", "age": 141}\r\n'
my_dic = json.loads(my_string)
print(my_dic, type(my_dic))

Which will result:

{'name': 'Bobby', 'age': 141} <class 'dict'>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading