【问题标题】:Is there a way to insert curly braces around text to make it a dictionary in string format?有没有办法在文本周围插入花括号以使其成为字符串格式的字典?
【发布时间】:2019-09-11 01:15:11
【问题描述】:

在我的 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, }"

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

【问题讨论】:

标签: python python-3.x dictionary text


【解决方案1】:

我猜你正在尝试将字典保存到文件中,* enter *: 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?

干杯!

【讨论】:

  • 这里使用json.dumpjson.load 直接读写文件会更有意义。
  • 我猜在 python 3 中的差异非常明显? stackoverflow.com/questions/36059194/…
  • 正如它在那个答案中所说,“如果你想将 JSON 转储到文件/套接字或其他任何东西中,那么你应该去dump() 如果你只需要它作为一个字符串然后使用dumps()。”同样,当你可以做 lson.load(f) 时,做 json.loads(f.read()) 是没有意义的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-06-23
  • 1970-01-01
  • 2015-07-06
  • 2019-12-27
  • 2018-11-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多