kaloon
kaloon

Reputation: 177

How to convert string containing dictionary to a dictionary?

Could anyone help me and explain to me why I keep getting an error? I have a string formatted as a dictionary. Similar to the below:

str1_dict="{Sentence:Frequently Asked Questions AND PRIVACY ,Question:What is the most frequently asked question about privacy?,Answer0:Frequently,Question:What does Privacy stand for?,Answer1:PRIVACY}"

I implemented a function that accepts the str1_dict and returns a value ( e.g., value of the key "Sentence.") Every time I run this function on the string str1_dict, I get the error:

  File "<string>", line 1
    {Sentence:Frequently Asked Questions AND PRIVACY ,Question:What is the most frequently asked question about privacy?,Answer0:Frequently,Question:What does Privacy stand for?,Answer1:PRIVACY}
                             ^
SyntaxError: invalid syntax

Here is my code:

import json

str1_dict="{Sentence:Frequently Asked Questions AND PRIVACY ,Question:What is the most frequently asked question about privacy?,Answer0:Frequently,Question:What does Privacy stand for?,Answer1:PRIVACY}"

def Read_dict(Data):
     line_tmp= Data.replace('\n','')
     jsn = eval(line_tmp)
     #jsn = json.loads(line_tmp)
     #jsn= ast.literal_eval(line_tmp)
     return jsn['Sentence']

 Read_dict(str1_dict)

I tried all the methods that I found online for converting string to dictionary, such as eval(), json.loads(), and ast.literal_eval(), but all of them failed. I keep getting the same error.

Can someone explain to me what wrong with my code or string?

Upvotes: 0

Views: 160

Answers (2)

TheEagle
TheEagle

Reputation: 5982

The problem is that your string does not contain valid JSON. You can use this function to parse your invalid JSON in a dictionary:

def str2dict(data):
    data = data.strip(" {}") # get rid of brackets and spaces at the start an end
    key_value_pair_strings = data.split(",") # split data at , into key value pair strings
    key_value_pair_strings_stripped = list(map(str.strip, key_value_pairs)) # strip whitespaces from the key value pair strings
    key_value_pairs = list(map(lambda s: s.split(":"), key_value_pair_strings)) # get key value pairs by splitting each key value pair string at :
   return dict(key_value_pairs)

result = str2dict("{Sentence:Frequently Asked Questions AND PRIVACY ,Question:What is the most frequently asked question about privacy?,Answer0:Frequently,Question:What does Privacy stand for?,Answer1:PRIVACY}")
print(result["Sentence"])

The whole function body can be reduced to one line !

def str2dict_one_line(data):
    return dict(list(map(lambda s: s.split(":"), list(map(str.strip, data.strip(" {}").split(","))))))

result = str2dict_one_line("{Sentence:Frequently Asked Questions AND PRIVACY ,Question:What is the most frequently asked question about privacy?,Answer0:Frequently,Question:What does Privacy stand for?,Answer1:PRIVACY}")
print(result["Sentence"])

Upvotes: 1

sehan2
sehan2

Reputation: 1835

You are missing the correct apostrophes:

On popular demand, you can also do this:

import json
str1_dict='{"Sentence": "Frequently Asked Questions AND PRIVACY" ,"Question": "What is the most frequently asked question about privacy?", "Answer0": "Frequently", "Question": "What does Privacy stand for?", "Answer1": "PRIVACY"}'
json.loads(str1_dict)

You can also use eval but know that it might not be safe and should be avoided or used with caution depending on your usecase:

str1_dict="{'Sentence': 'Frequently Asked Questions AND PRIVACY', 'Question': 'What is the most frequently asked question about privacy?', 'Answer0': 'Frequently', 'Question': 'What does Privacy stand for?', 'Answer1': 'PRIVACY'}"
eval(str1_dict)

Upvotes: 1

Related Questions