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).