Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

67890 pen 78

11223 olive 100

33344 book 18

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

>Solution :

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']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading