Bob
Bob

Reputation: 1396

Python: String to Dictionary

I've read through a couple StackOverflow posts on turning a string into a dictionary. I am trying to follow an example using ast.literal_eval and can't figure out where i'm going wrong. I believe i'm putting the string in the right format...

String: "{'platform_name': 'TSC2_commander', 'tracks': '52', 'time': '150'}"

Code: newdictionary = ast.literal_eval('"' + str(word) +'"')

But when I try to print print(newdictionary.get('Platform_Name')) I get "Str object has no attribute 'get'. Can someone teach me what i'm doing wrong?

Upvotes: 0

Views: 665

Answers (3)

Beaudry Chase
Beaudry Chase

Reputation: 195

The problem is with how ast is interpreting the string you give it. If the string of the dictionary itself does not contain quotes, it will be interpreted as what you intend.

    >>> import ast
    >>> dictionary = ast.literal_eval("{'a': 1, 'b': 2}")
    >>> print(type(dictionary))
    <class 'dict'>
    >>> dictionary.get('a')
    1

But if the string you give ast itself has quotes around it, it will be interpreted as a string.


    >>> newdictionary = ast.literal_eval('"' + str("{'a':1, 'b':2}") + '"')
    >>> print(type(newdictionary))
    <class 'str'>
    >>> print(newdictionary)
    {'a':1, 'b':2}
    >>>

Upvotes: 2

Dharmesh Fumakiya
Dharmesh Fumakiya

Reputation: 2338

Please take a look sample output:

import ast
my_string = "{'key':'val','key1':'value'}"
my_dict = ast.literal_eval(my_string)

Output:

{'key': 'val', 'key1': 'value'}

Upvotes: 1

rdas
rdas

Reputation: 21285

from ast import literal_eval
a_string = "{'platform_name': 'TSC2_commander', 'tracks': '52', 'time': '150'}"

a_dict = literal_eval(a_string)
print(a_dict['platform_name'])

Output:

TSC2_commander

Upvotes: 3

Related Questions