How to display all data in shelve in order?
Asked Answered
L

2

5

This is the first time I post in stack overflow. Perhaps I can get the solution that I need.

busdata=shelve.open("Database")
for lctno in busdata.keys():
    outputLine( lctno , busdata[ lctno ])

It randomly display the data in my .dat file. I want it to display in ascending order.

Litigant answered 17/10, 2015 at 16:57 Comment(1)
You could use sorted(busdata.keys()) but a shelve is inherently unordered.Stumpy
V
7

As g.d.d.c suggested, the solution is to sort the keys for yourself.

busdata=shelve.open("Database")
my_keys = list(bustdata.keys())
my_keys.sort()
for lctno in my_keys:
    outputLine( lctno , busdata[ lctno ])
Viridissa answered 23/3, 2017 at 3:10 Comment(0)
B
2

Since the code above did not work for me - I made some tests, and thought of posting my final working result (in full) - solving the listing of all data in shelve in order:

#!/usr/bin/python
# 

import shelve

def main():
    db = shelve.open("database.db")
    dkeys = list(db.keys())
    dkeys.sort()
    for x in dkeys:
        print ( x , db[ x ])
    db.close()
    return

if __name__ == "__main__":
    main()
Bughouse answered 13/2, 2019 at 10:18 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.