我有這段代碼
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
所以,也許有人知道如何做同樣的事情,但是使用擱置模塊?
uj5u.com熱心網友回復:
由于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']
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/431525.html
上一篇:以字串開頭的鍵的子集字典
