我有一段代码,其中在文本文件中输出字典,我有一个问题是否可以使用搁置模块来完成?

发布于 2025-01-09 11:57:39 字数 435 浏览 2 评论 0原文

我有这段代码

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 paper 3

67890 pen 78

11223 olive 100

33344 book 18

那么,也许有人知道如何做同样的事情,但使用搁置模块?

I have this piece of code

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

When this code is executed I have this result:

12345 paper 3

67890 pen 78

11223 olive 100

33344 book 18

So, maybe someone knows how to do the same, but using the shelve module?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

谁的新欢旧爱 2025-01-16 11:57:39

由于 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']

Since shelve shelves smell like dictionaries, you can just use .update() to write that dict into a shelf, then .items() to read:

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)

Output:

67890 ['pen', '78']
12345 ['paper', '3']
11223 ['olive', '100']
33344 ['book', '18']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文