How should python dictionaries be stored in pytables?

こ雲淡風輕ζ 提交于 2021-02-18 10:40:53

问题


pytables doesn't natively support python dictionaries. The way I've approached it is to make a data structure of the form:

tables_dict = {
'key'         : tables.StringCol(itemsize=40),
'value'       : tables.Int32Col(),
}

(note that I ensure that the keys are <40 characters long) and then create a table using this structure:

file_handle.createTable('/', 'dictionary', tables_dict)

and then populate it with:

file_handle.dictionary.append(dictionary.items())

and retrieve data with:

dict(file_handle.dictionary.read())

This works ok, but reading the dictionary back in is extremely slow. I think the problem is that the read() function is causing the entire dictionary to be loaded into memory, which shouldn't really be necessary. Is there a better way to do this?


回答1:


You can ask PyTables to search inside the table, and also create an index on the key column to speed that up.

To create an index:

table.cols.key.createIndex()

To query the values where key equals the variable search_key:

[row['value'] for row in table.where('key == search_key')]

http://pytables.github.com/usersguide/optimization.html#searchoptim



来源:https://stackoverflow.com/questions/9002433/how-should-python-dictionaries-be-stored-in-pytables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!