gpt4 book ai didi

python 3 保存字典

转载 作者:行者123 更新时间:2023-11-28 20:47:35 29 4
gpt4 key购买 nike

我已经看过关于 SO 的其他问题,比如这个问题,但它们对我来说太技术化了,无法理解(才学了几天)。我正在制作电话簿,我正在尝试像这样保存字典,

numbers = {}
def save(a):
x = open("phonebook.txt", "w")
for l in a:
x.write(l, a[l])
x.close()

但我得到错误 write() 只接受 1 个参数,obv im 传递 2,所以我的问题是我如何以初学者友好的方式做到这一点,你能用一种非技术性的方式描述它吗?非常感谢。

最佳答案

最好用json将字典转储到文件/从文件加载字典的模块:

>>> import json
>>> numbers = {'1': 2, '3': 4, '5': 6}
>>> with open('numbers.txt', 'w') as f:
... json.dump(numbers, f)
>>> with open('numbers.txt', 'r') as f:
... print json.load(f)
...
{u'1': 2, u'3': 4, u'5': 6}

关于python 3 保存字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18552587/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com