Is there a way to insert curly braces around text to make it a dictionary in string format?
在我的python程序中,我有一个添加到文本文件中的键和值的列表,我需要能够提取这个字符串列表并将其转换为字典。
例如:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | counter = 0 add = str(counter) counterDict = UserID +":" + add +"," counter = counter + 1 #This should make counterDict look like:""Smi39119": 0,"Joh38719": 1," etc. f = open("Dictionaries.txt","a") f.write(counterDict) f.close() #Then I would like to be able to open the file and turn that string into a dictionary f = open("Dictionaries.txt","r") string = f.read() #This way 'string' should still be a string, but look like this:"{"Smi39119": 0,"Joh38719": 1, }" |
我不知道这是否可能,但如果可能,所有的解决方案都会非常感谢。
我猜你是想把字典保存到一个文件中,*回车*:json文件系统,您不需要将字典转换为字符串,让JSON将其转换为字符串。
1 2 3 4 5 6 7 8 9 10 | import json f = open("Dictionaries.json","a") f.write(json.dumps(your_dictionary)) f.close() # load it and use it like a dictionary f = open("Dictionaries.json","r") your_dictionary = json.loads(f.read()) |
还读写一个dict到txt文件和读回来?
干杯!