添加到不带引号的python列表

时间:2019-05-16 01:58:35

标签: python json

如何在不引起引号引起json错误的引号的情况下添加到我的python列表中?

classes["class1"] = "{'key1': 1, 'key2': 2, 'key3': 3}"

那就是我得到的:

  'class1': "{
      'key1': 1,
      'key2': 2,
      'key3': 3
  }"

4 个答案:

答案 0 :(得分:0)

import ast 

classes["class1"] = ast.literal_eval("{'key1': 1, 'key2': 2, 'key3': 3}")

答案 1 :(得分:0)

尝试一下:

df1 <- structure(list(a = c(2L, 2L, 3L, 4L), b = c(3L, 4L, 7L, 1L), 
    num_days = c("01Y", "", "01Y02M", "0"), d = c(99L, 8L, 7L, 
    8L)), class = "data.frame", row.names = c(NA, -4L))

答案 2 :(得分:0)

import json
classes={}
classes["class1"] = json.loads("{'key1': 1, 'key2': 2, 'key3': 3}".replace("'",'"'))
print(classes["class1"])

答案 3 :(得分:0)

使用ast.literal_eval将字符串"{'key1': 1, 'key2': 2, 'key3': 3}"解析为字典。

In [16]: import ast                                                                                                                                                                                     

In [17]: classes = {}                                                                                                                                                                                   

In [18]: classes["class1"] = ast.literal_eval("{'key1': 1, 'key2': 2, 'key3': 3}")                                                                                                                      

In [19]: classes                                                                                                                                                                                        
Out[19]: {'class1': {'key1': 1, 'key2': 2, 'key3': 3}}

请注意,由于字符串中的单引号,因此您不能在此处使用json.loads

In [20]: import json                                                                                                                                                                                    

In [21]: classes = {}                                                                                                                                                                                   

In [22]: classes["class1"] = json.loads("{'key1': 1, 'key2': 2, 'key3': 3}")                                                                                                                            
---------------------------------------------------------------------------
JSONDecodeError                           Traceback (most recent call last)
<ipython-input-22-592615e01642> in <module>
----> 1 classes["class1"] = json.loads("{'key1': 1, 'key2': 2, 'key3': 3}")

JSONDecodeError: Expecting property name enclosed in double quotes: 
line 1 column 2 (char 1)