在运行时附加到字典

发布于 2024-09-28 22:58:20 字数 2517 浏览 7 评论 0原文

我有一个名为 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()

I have a function named OpenAccount() which takes in the details from the User and appends it to my database dictionary.

I have a database file(module) which is imported in my function file.

I have a function called AppendRecord(key,**dictvalues) which appends values to my database file.

However I am not able to call the function and take in values at run-time to append.
It works fine with Hard-coded values.I'm posting the code.Please help me out.

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

and the call for hard coded values is ...

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

Now when I' trying to take in all the values along with the key from the user,I am not able to call the function.I'm just a beginner at Python so please pardon me for any errors:

Edited Code:

#!/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)

EDIT 1:
The Errors I get are.

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

EDIT 2:

Following is the DB.py database file source code.

#!/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()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

只为守护你 2024-10-05 22:58:20

您的问题是 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 并添加了几乎为零的值。我会废弃整个DB模块并直接使用shelve

Your problem is that the DB module is closing the shelf before you write to it. Get rid of the last line and it will work fine.

You will also need to provide a function to close it or do so manually.

#!/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()

You will now need to call the DB.open_shelf() function before you write to it and the DB.close_shelf function when you are done. I would recommend calling them at the beginning and end of your program respectively.

You'll note that this is really just wrapping shelve and adding pretty much zero value. I would scrap the whole DB module and just use shelve directly.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文