[Tutor] Dictionary within a dictionary

Alan Gauld alan.gauld at btinternet.com
Fri Jun 13 02:32:11 CEST 2008


<qsqgeekyogdty at tiscali.co.uk> wrote


> I am presuming that each of these tables is one of my 
> dictionaries?!?!
> What I don't understand is how to write this SQL statement in python
> code:
>
> SELECT id, category from Categories WHERE group_id = "1";

SQL is designed(and optimised) for doing complex data queries.

If you are doingcomplex queries the best and fastest solution
will almost certainly be to use SQL from Python rather than
trying to build your own database using nested dictionaries
and queries.

Pythons dbapi can interface to most available database packages.
If you don't already have one Python 2.5 comes with SqlLite in
the standard library, which is basic but effective for small projects!

> Can some one help me understand how to pass the group_id in a simple
> example, so that I can return all the categories from Category 
> table.

This is possibly but messy.

# items = {group: [(name,category)....]}

items = {1 : [('foo', 'hero'), ('bar','villian')],
             2: [(darth', 'villian'), ('luke', 
'hero'),('han','hero')]}

result = [(item[1],item[0]) for item in items[1]]

is equivalent to saying

SELECT category,name from items where group = 1

But you need to design your data structure carefully to keep the
query as simple as that.

> I am using the SQL example to figure it out in my head - perhaps 
> this
> is a wrong way to look at this?

On the contrary, SQL is almost certainly the best way, not only
to think about it, but to implement it! Use the right tool for the 
job.


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list