运行时向字典添加项

1 投票
1 回答
3009 浏览
提问于 2025-04-16 06:00

我有一个叫做 OpenAccount() 的函数,它会接收用户的详细信息,然后把这些信息添加到我的数据库字典里。

我有一个数据库文件(模块),在我的函数文件中导入了这个数据库。

我还有一个叫做 AppendRecord(key, **dictvalues) 的函数,它负责把值添加到我的数据库文件中。

不过,我在运行时无法调用这个函数来接收值进行添加。用硬编码的值时是可以正常工作的。我把代码贴出来了,希望能得到帮助。

def AppendRecord(key, **dictvalues):
      salesDept[key] = dict(dictvalues)

而硬编码值的调用方式是……

AppendRecord('Jill',Name='Jill', Acctype='Savings')

现在,当我尝试从用户那里获取所有值和键时,我无法调用这个函数。我刚开始学Python,所以如果有错误请多包涵:

编辑后的代码:

#!/usr/bin/python

import os       #This module is imported so as to use clear function in the while-loop
import DB                       #Imports the data from database DB.py

def AppendRecord(key, **dictvalues):
        DB.Accounts[key] = dict(dictvalues)

def OpenAccount():           #Opens a new a/c and appends to the database   data-base.

        while True:

                os.system("clear")      #Clears the screen once the loop is re-invoked

#Parameters taken from the user at Run-time so as to make entries in the database and append them


                print '\n','Choose an Account Type'

                print '\n','\n1)Savings Account','\n2)Current Account'

                choice = input('Enter an optin: ')

                if choice == 1:

                        name = raw_input('\nEnter a name: ')
                        depo = input('\nEnter amount(Rs.): ')
                        key = raw_input('\nEnter an alphanumeric-id: ')
                        acc= raw_input('\nEnter the Account-Type: ')

                        AppendRecord(key,Name=name,Initial_deposit=depo,Acctype=acc)

编辑 1: 我遇到的错误是:

 File "/usr/lib/python2.5/shelve.py", line 124, in __setitem__
    self.dict[key] = f.getvalue()
TypeError: 'int' object does not support item assignment

编辑 2:

以下是 DB.py 数据库文件的源代码。

#!/usr/bin/python

import shelve                   #Module:Shelve is imported to achieve persistence

Victor = {'Name':'Victor Hughes','Acctype':'Savings'}
Xavier = {'Name':'Xavier Bosco','Acctype':'Savings'}
Louis = {'Name':'Louis Philip','Acctype':'Current'}
Beverly = {'Name':'Beverly Dsilva','Acctype':'Current'}

Accounts = shelve.open('shelfile.shl')          #Accounts = {}

Accounts['Louis']= Louis
Accounts['Beverly']= Beverly
Accounts['Xavier']= Xavier
Accounts['Victor']= Victor

Accounts.close()

1 个回答

1

你的问题是,DB模块在你写入之前就把架子关掉了。把最后一行去掉,它就能正常工作了。

你还需要提供一个函数来关闭它,或者手动去关闭。

#!/usr/bin/python

import shelve                   #Module:Shelve is imported to achieve persistence


Accounts = 0

Victor = {'Name':'Victor Hughes','Acctype':'Savings'} #???
Xavier = {'Name':'Xavier Bosco','Acctype':'Savings'}
Louis = {'Name':'Louis Philip','Acctype':'Current'}
Beverly = {'Name':'Beverly Dsilva','Acctype':'Current'}


def open_shelf(name='shelfile.shl'):
    global Accounts
    Accounts = shelve.open(name)          #Accounts = {}
    # why are you adding this every time? is this just debugging code?
    Accounts['Louis']= Louis
    Accounts['Beverly']= Beverly
    Accounts['Xavier']= Xavier
    Accounts['Victor']= Victor


def close_shelf():
    Accounts.close()

现在你需要在写入之前调用DB.open_shelf()函数,完成后再调用DB.close_shelf函数。我建议你在程序的开始和结束时分别调用这两个函数。

你会发现,这其实只是对shelve进行了简单的封装,几乎没有增加什么价值。我建议直接使用shelve,而不是整个DB模块。

撰写回答