简体   繁体   中英

Add to python list without quotations

How can I add to my python list without quotations that cause a json error?

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

Thats what I get:

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

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

Try this:

>>> def print_sameline():
...     list = [1,2,3]
...     print("List: ",end="")
...     print(*list,sep=",")
... 
>>> print_sameline()
List: 1,2,3
import json
classes={}
classes["class1"] = json.loads("{'key1': 1, 'key2': 2, 'key3': 3}".replace("'",'"'))
print(classes["class1"])

Use ast.literal_eval to parse the string "{'key1': 1, 'key2': 2, 'key3': 3}" to a dictionary.

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}}

Note that you cannot use json.loads here due to the single quotes in your string

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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