Py学习  »  Python

添加到不带引号的python列表

user-2147482276 • 4 年前 • 816 次点击  

如何在没有导致json错误的引号的情况下添加到python列表?

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

这就是我得到的:

  'class1': "{
      'key1': 1,
      'key2': 2,
      'key3': 3
  }"
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/52832
 
816 次点击  
文章 [ 4 ]  |  最新文章 4 年前
Nadhem Maaloul
Reply   •   1 楼
Nadhem Maaloul    4 年前
import json
classes={}
classes["class1"] = json.loads("{'key1': 1, 'key2': 2, 'key3': 3}".replace("'",'"'))
print(classes["class1"])
Nam V. Do
Reply   •   2 楼
Nam V. Do    4 年前

试试这个:

>>> def print_sameline():
...     list = [1,2,3]
...     print("List: ",end="")
...     print(*list,sep=",")
... 
>>> print_sameline()
List: 1,2,3
Jose Angel Sanchez
Reply   •   3 楼
Jose Angel Sanchez    4 年前
import ast 

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

Devesh Kumar Singh
Reply   •   4 楼
Devesh Kumar Singh    4 年前

使用 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)