向现有字典添加值的更快方法?

2024-05-16 20:50:50 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本词典

#Initialize the dictionary
myDict=dict()
for f in ncp:
    myDict[f]={}
    for t in ncp:
        myDict[f][t] = {}

现在我遍历并添加一个值到最低级别(恰好是dictionary键,值为None),就像这样,但是我当前的方法非常慢

for s in subsetList:
    stIndex = 0
    for f in list(allNodes.intersection(set(s)))
            for t in list(allNodes.difference(set( allNodes.intersection(s)))):
                myDict[f][t]['st_'+str(stIndex)]=None
    stIndex+=1

我试着用理解的原则去做,但是我失败了,因为我找到的理解的例子是创建字典,而不是重复一个已经存在的要添加的字典。我这样做的尝试甚至不会“编译”:

myDict[f][t]['st_'+str(stIndex)]
    for f in list(allNodes.intersection(set(s)))
       for t in list(allNodes.difference(set( allNodes.intersection(s)))) = None

Tags: innonefordictionary字典mydictlistst
3条回答

这应该更快。。。你知道吗

from itertools import product
from collections import defaultdict

mydict = defaultdict(dict)
for f, t in  product(ncp, repeat=2):
    myDict[f][t] = {}
    for s in subsetList:
        myDict[f][t]['st_'+str(stIndex)] = None

或者如果最里面的键级别每次都相同。。。你知道吗

from itertools import product
from collections import defaultdict

innerDict = {}
for s in subsetList: 
    innerDict['st_'+str(stIndex)] = None

mydict = defaultdict(dict)
for f, t in  product(ncp, repeat=2):
    myDict[f][t] = innerDict.copy()

但我不确定创建最里面字典的副本是否比每次遍历子列表并创建新字典更快。你需要给这两个选项计时。你知道吗

在这里用一个关于最佳方法的理论来回答我自己的问题,经过多次尝试:最终的结果是myDict,它是由两个元素组成的函数:allNodes和subsetList,这两个元素实际上都是在我的程序开始时从SQL导入的静态表。所以,为什么不计算一次myDict并将其存储在SQL中,同时导入它呢。因此,不是每次程序运行时都重建它(需要2分钟),它只是几秒钟的读取时间。我知道这是一种逃避,但它暂时有效。你知道吗

我会这样写你的代码:

myDict = {}
for i, s in enumurate(subsetList):
    tpl = ('st_%d' % (i,), None) # Used to create a new {'st_n': None} later
    x = allNodes.intersection(s)
    for f in x:
        myDict[f] = {}
        for t in allNodes.difference(x):
            myDict[f][t] = dict([tpl])

这减少了您需要创建的新对象的数量,以及按需初始化myDict。你知道吗

相关问题 更多 >