用for语句命名变量

时间:2019-06-10 18:19:45

标签: python-3.x shelve

这是一个较大的代码项目的一部分,但我对项目的这一部分感到困惑。

我正在寻找一家货架商店来存储其中的各种词典。这些名称取决于我进入for循环的距离(取决于用户输入的信息(选择有多少数据集))

此刻我的代码抛出错误

import shelve

#opening a data file
f = shelve.open('data', flag='c', writeback=True)

#getting some the number for the loops (which I call data sets)

numDataPoints = int(input('Enter the number of data sets:\n'))

#Has the loop, starting at 1, ending with the number entered into numDataPoints
for i in range(1, numDataPoints +1):

        #reopening just in case :-)
    f = shelve.open('data', flag='c', writeback=True)

        #getting a value which I want to store later

    val1 = float(input("Enter independent value for data point " + str(i) +": "))

        #getting another number for the next loop within this data point loop
    rep = int(input('Enter the number of repeats: '))

        #saving the data I already have to a dictionary (not in.a shelve file)
    diction = {'val1': val1, 'reps': rep}

        #starting the new loop for each repeat, similar way to before
    for x in range(1, rep+1):
                #find out another user input value which I want to get stored
        val2 =  float(input('Enter dependent variable value for repeat number ' + str(x) + ':'))
                #saving this value to the dictionary with the repetition number as the key
        diction['rep'+str(x)] = val2



        #This is where the problem is as I am trying to save all this information that I have stored in the 'diction' dictionary into a shelve file under a dictionary in the shelve file, so that I can call it back later. The 'i' refers back to the first for loop

    f[str(locals()["group".format(str(i))])] = diction
    f.sync()

#This is just to test and see if they all saved properly 
for key in f:
    print(f[key])

f.close()

出现以下错误: 追溯(最近一次通话):

File "/Users/thomasholland/PycharmProjects/sdak_local/test.py", line 23, in <module>
    f[str(locals()["group".format(str(i))])] = diction
KeyError: 'group1'

我希望将字典(字典)保存到架子上,就像我正常输入字典一样。我认为问题在于该group1不可编辑,但我不知道如何使其可用。

0 个答案:

没有答案