如何使用字典为单个键赋予多个值? [英] How to give multiple values to a single key using a dictionary?

查看:305
本文介绍了如何使用字典为单个键赋予多个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个html表单,它具有名字 LastName 年龄性别 ADD 按钮。
我将数据输入到表单中,并进入Berkeelys数据库。我的代码是只打印最后的值。我想要它应该显示与特定键相关的所有值

 #!/ usr / bin / python 

import bsddb
import cgi

form = cgi.FieldStorage()

printContent-type:text / html\\\

Fname = form.getvalue('firstname','')
Lname = form.getvalue('lastname','')
年龄= form.getvalue('age',0)
Gender = form.getvalue('gender','')

#print Fname,Lname,Age

db = bsddb.hashopen(/ home / neeraj / public_html /database/mydb.db\",\"w)
db ['FirstName'] = Fname
db ['LastName'] = Lname
db ['Age'] =年龄
db ['Gender'] =性别
db.close()
db = bsddb.hashopen(/ home / neeraj / public_html / database / mydb.db,r)
#db = bsddb.hashopen(/ home / neeraj / public_html / database / mydb.db)
打印db ['FirstName'],db ['LastName'],db ['Age'], db ['Gender']
db.close()
打印db


解决方案

您应该使用SQL数据库而不是基于 dict 的接口,因为SQL数据库已经处理了表中的多个元组。



无论如何,如果你想要一个 dict 界面,你可以使用 shelve module( bsddb 已被弃用,所以您应该避免这种情况)并将每个值保存在列表中

  import shelve 

COLUMNS =('FirstName','LastName','Age','Sex' )

the_db = shelve.open('test.db',writeback = True)
COLUMNS中的col_name:
如果col_name不在the_db中:
the_db [ col_name] = []

records = [
('John','Deer',20,'M'),
('Ada','Lovelace',23 ,'f'),
]

记录中的记录:
为col_name,值为zip(COLUMNS,记录):
the_db [col_name] .append (value)

the_db.close()

the_db = shelve.open('test.db')

用于在zip中记录(*(COLUMNS中col_name的__db [col_name]))
打印(记录)

the_db.close()

上述代码输出:

 ('John','Deer',20,'M')
('Ada','Lovelace',23''F')
pre>




如果要使用SQL数据库,可以使用 sqlite3 模块。
例如:

  import sqlite3 

conn = sqlite3.connect('test。 sqlite')

cursor = conn.cursor()

cursor.execute('''
CREATE TABLE people(
FirstName text,
姓氏文本,
年龄int,
性别文本
)''')

cursor.execute('''
INSERT INTO people values ('John','Deer',20,'M')''')

cursor.execute('''
INSERT INTO people values('Ada','Lovelace' ,23,'F')''')

conn.commit()

用于在cursor.execute('''SELECT * FROM people'')中记录) :
打印(记录)

上述代码输出:

 (u'John',u'Deer',20,u'M')
(u'Ada',u'Lovelace' 23,u'F')

(注意 u'... '只是意味着字符串是unicode,它不会改变它们的值)



但是这个代码有一些问题(例如,尝试运行它两次...),但如果你想遵循这个路径,那么你必须学习SQL ,所以继续坚持下去(有很多在线教程。例如 w3schools 一个)。


I have a html form which has Firstname, LastName, Age and Gender and a ADD button. I enter the data into the form and that gets into the Berkeelys db. What my code does is it prints only the last values. I want that it should show all the values related to particular key

#!/usr/bin/python

import bsddb
import cgi

form = cgi.FieldStorage()

print "Content-type:text/html\n"
Fname = form.getvalue('firstname', '')
Lname = form.getvalue('lastname', '')
Age = form.getvalue('age', 0)
Gender = form.getvalue('gender', '')

#print Fname, Lname, Age 

db = bsddb.hashopen("/home/neeraj/public_html/database/mydb.db","w")
db['FirstName'] = Fname  
db['LastName'] = Lname
db['Age'] = Age 
db['Gender'] = Gender
db.close()
db = bsddb.hashopen("/home/neeraj/public_html/database/mydb.db","r")
#db = bsddb.hashopen("/home/neeraj/public_html/database/mydb.db")
print db['FirstName'], db['LastName'], db['Age'], db['Gender']
db.close()
print db 

解决方案

You should use an SQL database instead of the dict-based interface, since SQL databases already handle multiple tuples in a table.

Anyway, if you want to have a dict interface you can use the shelve module (bsddb is deprecated, so you should avoid it) and save each value in a list:

import shelve

COLUMNS = ('FirstName', 'LastName', 'Age', 'Sex')

the_db = shelve.open('test.db', writeback=True)
for col_name in COLUMNS:
    if col_name not in the_db:
        the_db[col_name] = []

records = [
    ('John', 'Deer', 20, 'M'),
    ('Ada', 'Lovelace', 23, 'F'),
]

for record in records:
    for col_name, value in zip(COLUMNS, record):
        the_db[col_name].append(value)

the_db.close()

the_db = shelve.open('test.db')

for record in zip(*(the_db[col_name] for col_name in COLUMNS)):
    print(record)

the_db.close()

The above code outputs:

('John', 'Deer', 20, 'M')       
('Ada', 'Lovelace', 23, 'F')


If you want to use an SQL database you could use the sqlite3 module. For example:

import sqlite3

conn = sqlite3.connect('test.sqlite')

cursor = conn.cursor()

cursor.execute('''
CREATE TABLE people (
    FirstName text,
    LastName text,
    Age int,
    Sex text
    )''')

cursor.execute('''
INSERT INTO people values ('John', 'Deer', 20, 'M')''')

cursor.execute('''
INSERT INTO people values ('Ada', 'Lovelace', 23, 'F')''')

conn.commit()

for record in cursor.execute('''SELECT * FROM people'''):
    print(record)

The above code outputs:

(u'John', u'Deer', 20, u'M')
(u'Ada', u'Lovelace', 23, u'F')

(Note the u'...' simply means that the strings are unicode, it doesn't change their value)

However this code has some problems (e.g. try to run it twice...), but if you want to follow this path then you must learn SQL first, so go ahead and stufy it (there are a lot of online tutorials. For example w3schools ones).

这篇关于如何使用字典为单个键赋予多个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆