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
- Add more users to this data structure. A dictionary of dictionaries?
- Allow users to have more than one credit card, a many to one relationship
Thanks for any responses, I've been trying to wrap my head around this for awhile
-
2The real trouble is that this in-memory approach gets messy fast. If you have a dictionary of users, what do you use for the keys? What if there are duplicate keys? etc.Mike DeSimone– Mike DeSimone2012年05月30日 20:52:04 +00:00Commented May 30, 2012 at 20:52
-
By the way, you may be interested in this Python-related list of databases, particularly the native Python ones.kojiro– kojiro2012年05月30日 20:53:12 +00:00Commented May 30, 2012 at 20:53
5 Answers 5
You might be interested in SQLAlchemy. It makes an actual database, such as SQLite or MySQL, work more like Python classes.
Comments
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.
Comments
1 Comment
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']]}
1 Comment
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 lists and dicts. 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!