Reputation: 4668
My question is how to create a simple database in python. My example is:
User = {
'Name' : {'Firstname', 'Lastname'},
'Address' : {'Street','Zip','State'},
'CreditCard' : {'CCtype','CCnumber'},
}
Now I can update this User's information just fine, but how do I
Thanks for any responses, I've been trying to wrap my head around this for awhile
Upvotes: 7
Views: 21510
Reputation: 123463
Create a User
class to store the information. The class can have a creditcards
attribute which is a list
of CreditCard
class instances that get added to class instances either when they're created or later using a class method you can define. Other methods can update this (and other) attributes as necessary when called. It's called object-oriented programming (OOP).
Instances can be stored in memory within instances of a variety of built-in container classes such as list
s and dict
s. They can be stored onto disk and retrieved later using the pickle
, shelve
, json
, and sqlite3
modules, just to name a few.
You're not trying to do anything that hasn't been done before -- which is good news because it means there's lot of off-the-shelf software at your disposal, but you'll have to read up on them in the documentation and probably ask a few more questions until you've learned how to use them, then you can start answering questions. ;-)
Welcome to Python!
Upvotes: 4
Reputation: 798666
1. Add more users to this data structure. A dictionary of dictionaries?
A list of dictionaries.
[{'name': ...}, {'name': ...}]
2. Allow users to have more than one credit card, a many to one relationship
A list.
{'name': ..., 'creditcard': [['type', 'number'], ['type', 'number']]}
Upvotes: 4
Reputation: 77107
Most key-value stores I've seen are either a dictionary of dictionaries (like mongo*) or a dictionary of strings (like redis). There are pros and cons to both approaches. I don't know what you want, so I'll give the simplest answer: Go with a list of dictionaries:
Users = []
Users.append({
'Name' : {'Firstname', 'Lastname'}, # Are these sets?
'Address' : {'Street','Zip','State'},
'CreditCard' : {'CCtype','CCnumber'},
})
*OK, to be fair, Mongo is more like a dictionary of magic strings. It's json, but the lookups are handled internally, so you can treat it like a dictionary of arbitrary (but json-serializable) data structures.
Upvotes: 5
Reputation: 11585
You can create a simple database in Python with sqlite, here's a basic tutorial for it.
Upvotes: 4
Reputation: 42805
You might be interested in SQLAlchemy. It makes an actual database, such as SQLite or MySQL, work more like Python classes.
Upvotes: 11