简体   繁体   English

Python将字符串转换为字典

[英]Python Convert string to dict

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 ? 有任何想法吗 ?

This has been settled in 988251 In short; 简而言之,这已在988251中解决。 use the python ast library's literal_eval() function. 使用python ast库的literal_eval()函数。

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

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. 现在字典包含您要查找的数据结构。

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,因此现在您可以使用json模块轻松将其解析为Python dict

import json

parsed = json.loads(output)
# {'livestock': {'sheep': '2', 'cow': '5'}, 'tomatoes': '5'}

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 . 我的策略是通过eval将字典str转换为dict 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. 从错误消息中,我提取了被解释为未知变量的键,并用引号将其引起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM