有没有办法在文本周围插入花括号以使其成为字符串格式的字典?

时间:2019-04-21 16:02:38

标签: python python-3.x dictionary text

在我的python程序中,我有一个添加到文本文件中的键和值的列表,我需要能够提取此字符串列表并将其转换为字典。

例如:

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

我不知道这是否可行,但如果可以,所有解决方案将不胜感激。

1 个答案:

答案 0 :(得分:0)

我猜您正在尝试将字典保存到文件中,* 输入 *: json文件系统, 您无需将字典转换为字符串,让json来将其转储为字符串。

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())

另请参阅Writing a dict to txt file and reading it back?

欢呼!