How do I count and enumerate the keys in an lmdb with python?

Doug picture Doug · Sep 9, 2015 · Viewed 8.9k times · Source
import lmdb
env = lmdb.open(path_to_lmdb)

Now I seem to need to create a transaction and a cursor, but how do I get a list of keys that I can iterate over?

Answer

sytrus picture sytrus · May 4, 2016

A way to get the total number of keys without enumerating them individually, counting also all sub databases:

with env.begin() as txn:
    length = txn.stat()['entries']

Test result with a hand-made database of size 1000000 on my laptop:

  • the method above is instantaneous (0.0 s)
  • the iteration method takes about 1 second.