如何将包含字典的字符串转换为字典?

2024-06-16 14:13:43 发布

您现在位置:Python中文网/ 问答频道 /正文

谁能帮我解释一下为什么我总是出错? 我有一个格式化为字典的字符串。与以下内容类似:

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}"

我实现了一个函数,它接受str1_dict并返回一个值(例如,键"Sentence."的值) 每次在字符串str1_dict上运行此函数时,都会出现以下错误:

  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

这是我的密码:

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)

我尝试了在网上找到的所有将字符串转换为字典的方法,如eval()json.loads()、和ast.literal_eval(),但都失败了。我总是犯同样的错误

有人能解释一下我的代码或字符串有什么问题吗


Tags: and字符串evallinewhattmpdictsentence
2条回答

问题是您的字符串不包含有效的JSON。您可以使用此函数在字典中解析无效的JSON:

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"])

整个功能体可以减少到一行

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"])

您缺少正确的撇号:

根据大众需求,您也可以这样做:

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)

您也可以使用eval,但要知道它可能不安全,应根据您的用例避免或谨慎使用:

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)

相关问题 更多 >