首页 > 解决方案 > 在字典中返回特定列表的最快方法是什么?

问题描述

我在字典中的字典中有一个列表。数据集非常大。如果给定一个特定于键、字典对的列表,我如何才能最快地返回嵌套在两个字典中的列表?

{"Dict1":{"Dict2": ['UNIOUE LIST'] }} 

是否有替代数据结构可用于提高效率?

标签: pythonalgorithmsortingdata-structures

解决方案


我不相信 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

推荐阅读