我有一段代码,在文本文件中有字典的输出,我有一个问题,它是否可以用 shelve 模块来完成?
I have a piece of code with the output of dictionaries in a text file, and I had a question whether it can be done with the shelve module?
我有这段代码
dict3 = {'12345': ['paper', '3'], '67890': ['pen', '78'], '11223': ['olive', '100'], '33344': ['book',
'18']}
output = open("output.txt", "a", encoding='utf-8')
for k, v in dict3.items():
output.writelines(f'{k} {v[0]} {v[1]}\n')
output.close()
执行此代码时,我得到以下结果:
12345 篇论文 3
67890笔78
11223 橄榄 100
33344 本书 18
所以,也许有人知道如何做同样的事情,但使用搁置模块?
由于 shelve
书架闻起来像字典,您可以使用 .update()
将该字典写入书架,然后 .items()
阅读:
import shelve
dict3 = {
'12345': ['paper', '3'],
'67890': ['pen', '78'],
'11223': ['olive', '100'],
'33344': ['book', '18'],
}
with shelve.open("my.shelf") as shelf:
shelf.update(dict3)
# ...
with shelve.open("my.shelf") as shelf:
for k, v in shelf.items():
print(k, v)
输出:
67890 ['pen', '78']
12345 ['paper', '3']
11223 ['olive', '100']
33344 ['book', '18']
我有这段代码
dict3 = {'12345': ['paper', '3'], '67890': ['pen', '78'], '11223': ['olive', '100'], '33344': ['book',
'18']}
output = open("output.txt", "a", encoding='utf-8')
for k, v in dict3.items():
output.writelines(f'{k} {v[0]} {v[1]}\n')
output.close()
执行此代码时,我得到以下结果:
12345 篇论文 3
67890笔78
11223 橄榄 100
33344 本书 18
所以,也许有人知道如何做同样的事情,但使用搁置模块?
由于 shelve
书架闻起来像字典,您可以使用 .update()
将该字典写入书架,然后 .items()
阅读:
import shelve
dict3 = {
'12345': ['paper', '3'],
'67890': ['pen', '78'],
'11223': ['olive', '100'],
'33344': ['book', '18'],
}
with shelve.open("my.shelf") as shelf:
shelf.update(dict3)
# ...
with shelve.open("my.shelf") as shelf:
for k, v in shelf.items():
print(k, v)
输出:
67890 ['pen', '78']
12345 ['paper', '3']
11223 ['olive', '100']
33344 ['book', '18']