The anydbm module provides a generic interface allowing you to open databases based on several different lower-level packages that can be installed on the system. When imported, the anydbm module searches for the dbm, gdbm, or bsddb package. If none of those packages are available, the dumbdbm module is loaded and used for database I/O. The anydbm module provides the open(filename [,flag [, mode]]) function that allows you to open and create databases (see the "Opening and Closing Files" phrase of Chapter 4 for more details). Note When opening an existing database, anydbm uses the whichdb module to determine which database module to use when opening the database. Once the database has been opened, you can use the database object similarly to a dictionary. You can use the keys() and values() functions to retrieve a list of keys or values, respectively. You can also access a specific value by referencing using the corresponding key. import anydbm #Open DBM file for reading cityDB = anydbm.open("city.dbm", 'r') timeDB = anydbm.open("time.dbm", 'r') #Get keys flights = cityDB.keys() #Use keys to get values print "Arrivals" print "=============================================" for flight in flights: print ("Flight %s arrives from %s at %s" % (flight, cityDB[flight], timeDB[flight])) #Close DBM file cityDB.close() timeDB.close() get_dbm.py Arrivals ============================================= Flight 1144 arrives from Dallas at 230pm Flight 1045 arrives from Los Angeles at 320pm Flight 1520 arrives from New York at 420pm Output from get_dbm.py code |