pythondictionaryshelve

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

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