python - 在字典中返回特定列表的最快方法是什么?
问题描述
我在字典中的字典中有一个列表。数据集非常大。如果给定一个特定于键、字典对的列表,我如何才能最快地返回嵌套在两个字典中的列表?
{"Dict1":{"Dict2": ['UNIOUE LIST'] }}
是否有替代数据结构可用于提高效率?
解决方案
我不相信 Python 中存在更高效的数据结构。简单地使用常规索引运算符检索列表应该是一个非常快速的操作,即使两个级别的字典都非常大。
nestedDict = {"Dict1":{"Dict2": ['UNIOUE LIST'] }}
uniqueList = nestedDict["Dict1"]["Dict2"]
我对提高性能的唯一想法是尝试将数据结构扁平化为一个带有元组作为键的字典。这将比嵌套方法占用更多内存,因为顶级字典中的键将为二级字典中的每个条目复制,但它只会为每次查找计算一次哈希函数。但在实践中这种方法实际上比嵌套方法慢:
nestedDict = {i: {j: ['UNIQUE LIST'] for j in range(1000)} for i in range(1000)}
flatDict = {(i, j): ['UNIQUE LIST'] for i in range(1000) for j in range(1000)}
import random
def accessNested():
i = random.randrange(1000)
j = random.randrange(1000)
return nestedDict[i][j]
def accessFlat():
i = random.randrange(1000)
j = random.randrange(1000)
return nestedDict[(i,j)]
import timeit
print(timeit.timeit(accessNested))
print(timeit.timeit(accessFlat))
输出:
2.0440238649971434
2.302736301004188
推荐阅读
- c# - 如何在 Razor 中动态设置变量?
- postgresql - How to find postgresql query which is consuming the most I/O
- ruby-on-rails - AWS 运行 Rails 应用程序的架构指南(Web/Worker 设置)
- python - 使用 chunksize 从 read_sql_query 读取数据时将计数保留在变量中
- ios - 在当前操作之后将集合视图的委托设置为 self
- c# - 当一个条目具有多个属性时对列表进行排序?
- python - 无法获取所有子项(动态加载)硒 python
- excel - VBA 无法添加对指定 Word 模板的引用
- javascript - 如何使用航点滚动滚动到特定元素?
- node.js - 使用请求模块使用 node.js 将数据发布到 mojang api