Python将字符串转换为字典
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47663809/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Convert string to dict
提问by mwaks
I have a string :
我有一个字符串:
'{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'
and would like to convert it to
并想将其转换为
{
"tomatoes" : "5" ,
"livestock" :"{"cow" : "5" , "sheep" :"2" }"
}
Any ideas ?
有任何想法吗 ?
回答by cjor
回答by Natesh bhat
What u have is a JSON formatted string which u want to convert to python dictionary.
您拥有的是一个 JSON 格式的字符串,您想将其转换为 python 字典。
Using the JSON library :
使用 JSON 库:
import json
with open("your file", "r") as f:
dictionary = json.loads(f.read());
Now dictionary contains the data structure which ur looking for.
现在字典包含您要查找的数据结构。
回答by zwer
The problem with your input string is that it's actually not a valid JSON because your keys are not declared as strings, otherwise you could just use the json
module to load it and be done with it.
您的输入字符串的问题在于它实际上不是有效的 JSON,因为您的键没有声明为字符串,否则您可以使用json
模块加载它并完成它。
A simple and dirty way to get what you want is to first turn it into a valid JSON by adding quotation marks around everything that's not a whitespace or a syntax character:
获得所需内容的一种简单而肮脏的方法是首先通过在不是空格或语法字符的所有内容周围添加引号将其转换为有效的 JSON:
source = '{tomatoes : 5 , livestock :{cow : 5 , sheep :2 }}'
output = ""
quoting = False
for char in source:
if char.isalnum():
if not quoting:
output += '"'
quoting = True
elif quoting:
output += '"'
quoting = False
output += char
print(output) # {"tomatoes" : "5" , "livestock" :{"cow" : "5" , "sheep" :"2" }}
This gives you a valid JSON so now you can easily parse it to a Python dict
using the json
module:
这为您提供了一个有效的 JSON,因此现在您可以dict
使用该json
模块轻松地将其解析为 Python :
import json
parsed = json.loads(output)
# {'livestock': {'sheep': '2', 'cow': '5'}, 'tomatoes': '5'}
回答by innisfree
Here is my answer:
这是我的回答:
dict_str = '{tomatoes: 5, livestock: {cow: 5, sheep: 2}}'
def dict_from_str(dict_str):
while True:
try:
dict_ = eval(dict_str)
except NameError as e:
key = e.message.split("'")[1]
dict_str = dict_str.replace(key, "'{}'".format(key))
else:
return dict_
print dict_from_str(dict_str)
My strategy is to convert the dictionary str
to a dict
by eval
. However, I first have to deal with the fact that your dictionary keys are not enclosed in quotes. I do that by evaluating it anyway and catching the error. From the error message, I extract the key that was interpreted as an unknown variable, and enclose it with quotes.
我的策略是将字典转换str
为dict
by eval
。但是,我首先必须处理您的字典键没有用引号括起来的事实。我通过评估它并捕获错误来做到这一点。从错误消息中,我提取了被解释为未知变量的键,并用引号将其括起来。