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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:18:41  来源:igfitidea点击:

Python Convert string to dict

pythonstringdictionary

提问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

This has been settled in 988251In short; use the python astlibrary's literal_eval()function.

这个已经在988251解决了 总之;使用 pythonast库的literal_eval()函数。

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

回答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 jsonmodule 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 dictusing the jsonmodule:

这为您提供了一个有效的 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 strto a dictby 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.

我的策略是将字典转换strdictby eval。但是,我首先必须处理您的字典键没有用引号括起来的事实。我通过评估它并捕获错误来做到这一点。从错误消息中,我提取了被解释为未知变量的键,并用引号将其括起来。