tdc*_*tdc 9 python dictionary pytables
pytables本身不支持python词典.我接近它的方法是创建一个表单的数据结构:
tables_dict = {
'key' : tables.StringCol(itemsize=40),
'value' : tables.Int32Col(),
}
Run Code Online (Sandbox Code Playgroud)
(请注意,我确保密钥长度小于40个字符),然后使用此结构创建表:
file_handle.createTable('/', 'dictionary', tables_dict)
Run Code Online (Sandbox Code Playgroud)
然后用以下内容填充:
file_handle.dictionary.append(dictionary.items())
Run Code Online (Sandbox Code Playgroud)
和检索数据:
dict(file_handle.dictionary.read())
Run Code Online (Sandbox Code Playgroud)
这样做没问题,但重读字典非常慢.我认为问题是该read()函数导致整个字典被加载到内存中,这实际上并不是必需的.有一个更好的方法吗?
您可以要求PyTables在表内搜索,并在键列上创建索引以加快速度.
要创建索引:
table.cols.key.createIndex()
Run Code Online (Sandbox Code Playgroud)
要查询key等于变量的值search_key:
[row['value'] for row in table.where('key == search_key')]
Run Code Online (Sandbox Code Playgroud)
http://pytables.github.com/usersguide/optimization.html#searchoptim